Skip to content

Apache Lucene open-source search software

Build refactoring and cleanups (moving from build scripts to convention plugins) (#14764)

Dawid Weiss42123980c251
diff --git a/CHANGES-record.md b/CHANGES-record.md
new file mode 100644
index 00000000000..1172d73fe9b
--- /dev/null
+++ b/CHANGES-record.md
@@ -0,0 +1,112 @@
+<!--
+ 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 is a record of changes to the modernized gradle build.
+
+### ```buildOptions``` plugin instead of ```propertyOrDefault``` method
+
+All "propertyOrDefault*" methods have been removed and an external
+plugin for configuring various build options is now used. This is
+the plugin (blame me for any shortcomings):
+
+https://github.com/carrotsearch/gradle-build-infra#plugin-comcarrotsearchgradlebuildinfrabuildoptionsbuildoptionsplugin
+
+this plugin will source the value of a given build option from
+several places, in order:
+- system property (```-Dfoo=value```),
+- gradle property (```-Pfoo=value```),
+- environment variable (```foo=value ./gradlew ...```)
+- a *non-versioned*, ```build-options.local.properties``` property file
+ (for your personal, local tweaks),
+- a *versioned* ```build-options.properties``` property file.
+
+It works much like before - you can override any build option
+temporarily by passing, for example, ```-Ptests.verbose=true```. But you
+can also make such changes locally persistent by placing them
+in your ```build-options.local.properties``` file. Alternatively,
+the generated ```gradle.properties``` is also supported since it declares
+project properties (equivalent to ```-Pkey=value```). At some point
+in the future, we may want to keep gradle.properties versioned though,
+so it's probably a good idea to switch over to
+```build-options.local.properties```.
+
+The biggest gain from using build options is that you can now see
+all declared options and their values, including their source (where their
+value comes from). To see what I mean, try running these:
+```
+./gradlew :buildOptions
+./gradlew -p lucene/core buildOptions
+```
+
+### Lucene 'base version' string moved
+
+* Various Lucene's "version" properties are now full build options (as described above).
+Their default values are in ```build-options.properties```. You can override
+any of ```version.suffix```, ```version.base``` or ```version.release```
+using any of the build option plugin's methods. If you'd like to bump
+Lucene's base version, it now lives in the versioned ```build-options.properties```.
+
+### Tweaks to properties and options
+
+* ```runtime.java.home``` is a build option now but the support for
+```RUNTIME_JAVA_HOME``` env. variable has been implemented for backward
+compatibility.
+
+* ```tests.neverUpToDate``` option is renamed ```tests.rerun```.
+The value of ```true``` indicates test tasks will re-run even if
+nothing has changed.
+
+### Changes to project structure
+
+* ```build-tools/missing-doclet``` is now a regular project within Lucene (not
+an included composite project). This simplifies the build and ensures we apply
+the same checks to this subproject as we do to everything else.
+
+* all gradle build scripts are converted to convention plugins (in groovy) and
+live under ```dev-tools/build-infra/src/main/groovy```. The long-term
+plan is to move some or all of these groovy plugins to Java (so that the code is
+easier to read and debug for non-groovians).
+
+* ```tidy``` is now applied to groovy/gradle scripts (formatting is enforced).
+
+### Security manager support
+
+* parts of the build supporting security manager settings have been just
+removed, without any replacement.
+
+### Other notable changes
+
+* The legacy ```precommit``` task has been removed; use gradle's ```check```.
+
+* Removed dependency on jgit entirely. This is replaced by forking the system's git
+in porcelain mode (which should be stable and portable). This logic is implemented
+in [this plugin](https://github.com/carrotsearch/gradle-build-infra/?tab=readme-ov-file#plugin-comcarrotsearchgradlebuildinfraenvironmentgitinfoplugin).
+An additional benefit is that all features of git should now work (including worktrees).
+
+* Added support for owasp API keys in the form of ```validation.owasp.apikey``` build option. Owasp check is
+still very, very slow. We should probably just drop it.
+
+* I've changed the default on ```gradle.ge``` (Gradle Enterprise, develocity) to ```false```
+on non-CI builds.
+
+* I've tried to clean up lots and lots of gradle/groovy code related to eager initialization of
+tasks as well as update deprecated APIs. This isn't always straightforward and I might have broken
+some things...
+
+### Fixes to existing issues
+
+* ```gradlew clean check``` will work now (https://github.com/apache/lucene/issues/13567)
diff --git a/build-options.properties b/build-options.properties
new file mode 100644
index 00000000000..1370f0b9381
--- /dev/null
+++ b/build-options.properties
@@ -0,0 +1,16 @@
+#
+# These are various build options that the Lucene build uses.
+#
+# PLEASE READ ./gradlew helpLocalSettings
+#
+
+# This is the base Lucene version.
+version.base=11.0.0
+
+# This is the "suffix" added to version.base to form the final version.
+version.suffix=SNAPSHOT
+
+# This property is computed as ${version.base}-${version.suffix}; you
+# can override it manually to any x.y.z string to set an arbitrary
+# Lucene version.
+# version.release=
diff --git a/build-tools/build-infra-shadow/build.gradle b/build-tools/build-infra-shadow/build.gradle
new file mode 100644
index 00000000000..8b47d43a0c9
--- /dev/null
+++ b/build-tools/build-infra-shadow/build.gradle
@@ -0,0 +1,79 @@
+import com.diffplug.gradle.spotless.SpotlessTask
+
+/*
+ * 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.
+ */
+
+plugins {
+ id "java-gradle-plugin"
+}
+
+repositories {
+ mavenCentral()
+ gradlePluginPortal()
+}
+
+static Provider<String> plugin(Provider<PluginDependency> plugin) {
+ return plugin.map {
+ if (it.pluginId == "com.carrotsearch.gradle.buildinfra") {
+ return "${it.pluginId}:${it.pluginId}.gradle.plugin:${it.version}".toString()
+ } else if (it.pluginId == "de.thetaphi.forbiddenapis") {
+ return "de.thetaphi:forbiddenapis:${it.version}".toString()
+ } else {
+ return "${it.pluginId}:${it.pluginId.replaceFirst(".*\\.", "")}-plugin-gradle:${it.version}".toString()
+ }
+ }
+}
+
+dependencies {
+ implementation gradleApi()
+ implementation localGroovy()
+ implementation deps.commons.codec
+ implementation deps.randomizedtesting.runner
+
+ implementation plugin(deps.plugins.carrotsearch.buildinfra)
+ implementation plugin(deps.plugins.forbiddenapis)
+ implementation plugin(deps.plugins.spotless)
+}
+
+tasks.matching {
+ it.name in [
+ "renderSiteJavadoc",
+ "renderJavadoc",
+ "validateJarChecksums",
+ "validateJarLicenses",
+ "collectJarInfos",
+ "compileJava",
+ "compileTestJava",
+ "assemble"
+ ]
+}.configureEach {
+ enabled = false
+}
+
+// check spotless and other tasks into thinking their sources
+// are from build-infra.
+if (!isIdea) {
+ plugins.withType(JavaPlugin).configureEach {
+ SourceSet main = sourceSets.main
+ main.java.srcDirs = rootProject.files("build-tools/build-infra/src/main/java")
+ }
+
+ tasks.withType(SpotlessTask).configureEach {
+ it.projectDir.set(rootProject.file("build-tools/build-infra"))
+ it.target
+ }
+}
diff --git a/build-tools/build-infra-shadow/src/java/keep.me b/build-tools/build-infra-shadow/src/java/keep.me
new file mode 100644
index 00000000000..0d447c90f25
--- /dev/null
+++ b/build-tools/build-infra-shadow/src/java/keep.me
@@ -0,0 +1,2 @@
+Placeholder file to keep the directory in git. Triggers this project
+to be a java-library project (and applies all plugins in order).
\ No newline at end of file
diff --git a/build-tools/build-infra/build.gradle b/build-tools/build-infra/build.gradle
index 5cb1426cba9..e99c06ae817 100644
--- a/build-tools/build-infra/build.gradle
+++ b/build-tools/build-infra/build.gradle
@@ -17,25 +17,19 @@
plugins {
id "java-gradle-plugin"
+ id "groovy-gradle-plugin"
+
alias(deps.plugins.spotless) apply false
alias(deps.plugins.forbiddenapis) apply false
}
repositories {
mavenCentral()
+ gradlePluginPortal()
}
group = "org.apache"
-// Make sure the build environment is consistent.
-apply from: file('../../gradle/conventions.gradle')
-apply from: file('../../gradle/validation/check-environment.gradle')
-
-// Add spotless/ tidy.
-tasks.register("checkJdkInternalsExportedToGradle") {}
-apply from: file('../../gradle/validation/spotless.gradle')
-apply from: file('../../gradle/validation/forbidden-apis.gradle')
-
java {
sourceCompatibility = JavaVersion.toVersion(deps.versions.minJava.get())
targetCompatibility = JavaVersion.toVersion(deps.versions.minJava.get())
@@ -43,11 +37,20 @@ java {
gradlePlugin {
automatedPublishing = false
+}
- plugins {
- buildInfra {
- id = 'lucene.build-infra'
- implementationClass = 'org.apache.lucene.gradle.buildinfra.BuildInfraPlugin'
+// Convert a plugin dependency to a regular dependency so that we can
+// use [plugins] section in the top-level toml but declare regular
+// project dependencies here.
+static Provider<String> plugin(Provider<PluginDependency> plugin) {
+ return plugin.map {
+ if (it.pluginId == "de.thetaphi.forbiddenapis") {
+ // Uwe's forbiddenapis is on Maven Central, directly.
+ return "de.thetaphi:forbiddenapis:${it.version}".toString()
+ } else {
+ // maven artifact pattern for gradle's plugin repositories.
+ return "${it.pluginId}:${it.pluginId}.gradle.plugin:${it.version}".toString()
+ // return "${it.pluginId}:${it.pluginId.replaceFirst(".*\\.", "")}-plugin-gradle:${it.version}".toString()
}
}
}
@@ -56,11 +59,32 @@ dependencies {
implementation gradleApi()
implementation localGroovy()
implementation deps.commons.codec
+ implementation deps.randomizedtesting.runner
+ implementation deps.rat
+ implementation deps.zstd
+
+ implementation deps.flexmark.core
+ implementation deps.flexmark.ext.abbreviation
+ implementation deps.flexmark.ext.attributes
+ implementation deps.flexmark.ext.autolink
+ implementation deps.flexmark.ext.tables
+
+ implementation plugin(deps.plugins.carrotsearch.buildinfra)
+ implementation plugin(deps.plugins.forbiddenapis)
+ implementation plugin(deps.plugins.spotless)
+ implementation plugin(deps.plugins.owasp.dependencycheck)
+ implementation plugin(deps.plugins.undercouch.download)
+ implementation plugin(deps.plugins.errorprone)
}
+def hasJavaFlightRecorder = ModuleLayer.boot().findModule('jdk.jfr').map{ otherModule ->
+ this.getClass().module.canRead(otherModule)
+}.orElse(false)
if (!hasJavaFlightRecorder) {
logger.warn('Module jdk.jfr is not available; skipping compilation of Java Flight Recorder support.')
tasks.named('compileJava').configure {
exclude('**/ProfileResults.java')
}
}
+
+tasks.register("tidy", {})
diff --git a/build-tools/build-infra/settings.gradle b/build-tools/build-infra/settings.gradle
index 7bd479fc167..c64ad5885eb 100644
--- a/build-tools/build-infra/settings.gradle
+++ b/build-tools/build-infra/settings.gradle
@@ -18,9 +18,9 @@
rootProject.name = 'build-infra'
dependencyResolutionManagement {
- versionCatalogs {
- deps {
- from(files('../../gradle/libs.versions.toml'))
- }
+ versionCatalogs {
+ deps {
+ from(files('../../gradle/libs.versions.toml'))
}
+ }
}
diff --git a/gradle/hacks/gradle-archives.gradle b/build-tools/build-infra/src/main/groovy/lucene.all-projects.conventions.gradle
similarity index 51%
rename from gradle/hacks/gradle-archives.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.all-projects.conventions.gradle
index 363b6765140..95298f53cab 100644
--- a/gradle/hacks/gradle-archives.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.all-projects.conventions.gradle
@@ -13,11 +13,33 @@
* 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-9518: Set up sane defaults for any gradle archiving task.
-allprojects {
- tasks.withType(AbstractArchiveTask).configureEach { task ->
+// Common setup for all projects.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+allprojects {project ->
+ // All projects have the base plugin (convention tasks like 'check', etc.)
+ apply plugin: 'base'
+
+ // Project group and version.
+ group = "org.apache.lucene"
+ version = rootProject.version
+
+ // Source repositories for dependencies.
+ repositories {
+ mavenCentral()
+ }
+
+ // Common archive artifact naming.
+ var baseExt = project.getExtensions().getByType(BasePluginExtension)
+ baseExt.archivesName.convention(project.path.replaceAll("^:", "").replace(':', '-'))
+
+ // Common support for reproducible builds.
+ tasks.withType(AbstractArchiveTask).configureEach {
duplicatesStrategy = DuplicatesStrategy.FAIL
preserveFileTimestamps = false
reproducibleFileOrder = true
@@ -28,4 +50,10 @@ allprojects {
it.unix(0644)
}
}
+
+ // Common tasks or meta-tasks.
+ tasks.register("tidy", {
+ description "Applies all code formatters and other enforced cleanups to the project."
+ group "verification"
+ })
}
diff --git a/gradle/datasets/external-datasets.gradle b/build-tools/build-infra/src/main/groovy/lucene.datasets.external-datasets.gradle
similarity index 67%
rename from gradle/datasets/external-datasets.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.datasets.external-datasets.gradle
index b9601ebf6f7..4fb6d458e09 100644
--- a/gradle/datasets/external-datasets.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.datasets.external-datasets.gradle
@@ -1,5 +1,3 @@
-import java.nio.file.Files
-
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -17,34 +15,31 @@ import java.nio.file.Files
* limitations under the License.
*/
-buildscript {
- repositories {
- mavenCentral()
- }
+import java.nio.file.Files
+import com.github.luben.zstd.ZstdInputStream
+import de.undercouch.gradle.tasks.download.Download
+import org.apache.lucene.gradle.datasets.ExtractReuters
- dependencies {
- classpath deps.zstd
- }
+// tasks that download various benchmark/test data sets from the internet.
+
+// TODO: not sure whether this should live in benchmarks, but for now let it be.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
}
-def unzstd(java.nio.file.Path src, java.nio.file.Path dst) {
- try (InputStream is = new com.github.luben.zstd.ZstdInputStream(new BufferedInputStream(Files.newInputStream(src)));
- OutputStream os = new BufferedOutputStream(Files.newOutputStream(dst))) {
- is.transferTo(os)
+def static unzstd(java.nio.file.Path src, java.nio.file.Path dst) {
+ new ZstdInputStream(new BufferedInputStream(Files.newInputStream(src))).withCloseable { is ->
+ new BufferedOutputStream(Files.newOutputStream(dst)).withCloseable { os ->
+ is.transferTo(os)
+ }
}
}
-
-// TODO: not sure whether this should live in benchmarks, but for now let it be.
configure(project(":lucene:benchmark")) {
- apply plugin: "java"
- apply plugin: deps.plugins.undercouch.download.get().pluginId
+ def dataDir = project.file("work")
- ext {
- dataDir = file("work")
- }
-
- task getEnWiki(type: Download) {
+ def getEnWikiTask = tasks.register("getEnWiki", Download, {
ext {
name = "enwiki-20070527-pages-articles.xml"
src = "https://s3.amazonaws.com/lucene-testdata/wikipedia/${name}.zst"
@@ -52,6 +47,8 @@ configure(project(":lucene:benchmark")) {
dst = file("${dataDir}/${name}")
}
+ description "Download the ${ext.name} data set."
+
outputs.file ext.dst
src ext.src
@@ -63,9 +60,9 @@ configure(project(":lucene:benchmark")) {
logger.lifecycle("Decompressing ${ext.name}...")
unzstd(ext.intermediate.toPath(), ext.dst.toPath())
}
- }
+ })
- task getEnWikiRandomLines(type: Download) {
+ def getEnWikiRandomLinesTask = tasks.register("getEnWikiRandomLines", Download, {
ext {
name = "enwiki.random.lines.txt"
src = "https://s3.amazonaws.com/lucene-testdata/wikipedia/${name}.zst"
@@ -73,6 +70,8 @@ configure(project(":lucene:benchmark")) {
dst = file("${dataDir}/${name}")
}
+ description "Download the ${ext.name} data set."
+
outputs.file ext.dst
src ext.src
@@ -84,9 +83,9 @@ configure(project(":lucene:benchmark")) {
logger.lifecycle("Decompressing ${ext.name}...")
unzstd(ext.intermediate.toPath(), ext.dst.toPath())
}
- }
+ })
- task getGeoNames(type: Download) {
+ def getGeoNamesTask = tasks.register("getGeoNames", Download, {
// note: latest data is at: https://download.geonames.org/export/dump/allCountries.zip
// and then randomize with: gsort -R -S 1500M file.txt > file_random.txt
// and then compress with: bzip2 -9 -k file_random.txt
@@ -97,6 +96,8 @@ configure(project(":lucene:benchmark")) {
dst = file("${dataDir}/${name}")
}
+ description "Download the ${ext.name} data set."
+
outputs.file ext.dst
src ext.src
@@ -108,9 +109,9 @@ configure(project(":lucene:benchmark")) {
logger.lifecycle("Decompressing ${ext.name}...")
ant.bunzip2(src: ext.intermediate, dest: ext.dst)
}
- }
+ })
- task getTop100kWikiWordFiles(type: Download) {
+ def getTop100kWikiWordFilesTask = tasks.register("getTop100kWikiWordFiles", Download, {
ext {
name = "top.100k.words.de.en.fr.uk.wikipedia.2009-11"
src = "https://s3.amazonaws.com/lucene-testdata/wikipedia/${name}.tar.bz2"
@@ -118,6 +119,8 @@ configure(project(":lucene:benchmark")) {
dst = file("${dataDir}/${name}")
}
+ description "Download the ${ext.name} data set."
+
outputs.dir ext.dst
src ext.src
@@ -132,9 +135,9 @@ configure(project(":lucene:benchmark")) {
into ext.dst
}
}
- }
+ })
- task getReuters(type: Download) {
+ def getReutersTask = tasks.register("getReuters", Download, {
ext {
name = "reuters21578"
src = "https://kdd.ics.uci.edu/databases/${name}/${name}.tar.gz"
@@ -142,6 +145,8 @@ configure(project(":lucene:benchmark")) {
dst = file("${dataDir}/reuters-out")
}
+ description "Download the ${ext.name} data set."
+
outputs.dir ext.dst
src ext.src
@@ -162,29 +167,31 @@ configure(project(":lucene:benchmark")) {
logger.lifecycle("Extracting ${ext.name} into ${ext.dst}...")
ext.dst.deleteDir()
- buildinfra.extractReuters(untarPath.toString(), ext.dst.toString())
+ ExtractReuters.main(untarPath.toString(), ext.dst.toString())
}
- }
-
- task downloadDatasets() {
- group "Data set download"
- description "Download all data sets."
- }
-
- [
- getEnWiki,
- getGeoNames,
- getTop100kWikiWordFiles,
- getReuters,
- getEnWikiRandomLines
- ].each { task ->
- task.group "Data set download"
- task.description "Download the ${task.ext.name} data set."
-
- downloadDatasets.dependsOn(task)
-
- task.doFirst {
- logger.lifecycle("Downloading data set ${task.ext.name} from ${task.ext.src} to ${task.ext.dst}...")
+ })
+
+ def downloadTasks = [
+ getEnWikiTask,
+ getGeoNamesTask,
+ getTop100kWikiWordFilesTask,
+ getReutersTask,
+ getEnWikiRandomLinesTask
+ ]
+
+ tasks.register("downloadDatasets", {
+ group = "Data set download"
+ description = "Download all data sets."
+
+ dependsOn downloadTasks
+ })
+
+ downloadTasks.each {
+ it.configure {
+ group = "Data set download"
+ doFirst {
+ logger.lifecycle("Downloading data set ${it.ext.name} from ${it.ext.src} to ${it.ext.dst}...")
+ }
}
}
}
diff --git a/gradle/documentation/changes-to-html.gradle b/build-tools/build-infra/src/main/groovy/lucene.documentation.changes-to-html.gradle
similarity index 87%
rename from gradle/documentation/changes-to-html.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.documentation.changes-to-html.gradle
index 2d3f1f67d06..aead5f43e7b 100644
--- a/gradle/documentation/changes-to-html.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.documentation.changes-to-html.gradle
@@ -15,13 +15,17 @@
* limitations under the License.
*/
-def resources = scriptResources(buildscript)
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+File resources = rootProject.file("gradle/documentation/changes-to-html")
configure(project(':lucene:documentation')) {
- task changesToHtml(type: ChangesToHtmlTask) {
+ def changesToHtmlTask = tasks.register("changesToHtml", ChangesToHtmlTask, {
siteDir = resources
script = file("${resources}/changes2html.pl")
- }
+ })
// Make the rendered HTML of changes available as a separate
// artifact for the distribution.
@@ -30,8 +34,8 @@ configure(project(':lucene:documentation')) {
}
artifacts {
- changesHtml changesToHtml.targetDir, {
- builtBy changesToHtml
+ changesHtml changesToHtmlTask.get().targetDir, {
+ builtBy changesToHtmlTask
}
}
}
@@ -55,8 +59,8 @@ class ChangesToHtmlTask extends DefaultTask {
File siteDir
@OutputDirectory
- final DirectoryProperty targetDir = project.objects.directoryProperty()
- .fileProvider(project.providers.provider { project.file("${project.docroot}/changes") })
+ final DirectoryProperty targetDir = project.objects.directoryProperty().fileProvider(
+ project.providers.provider { project.file("${project.ext.docroot}/changes") })
@Input
def luceneDocUrl = "${-> project.luceneDocUrl }"
diff --git a/gradle/documentation/check-broken-links.gradle b/build-tools/build-infra/src/main/groovy/lucene.documentation.check-broken-links.gradle
similarity index 85%
rename from gradle/documentation/check-broken-links.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.documentation.check-broken-links.gradle
index 844380cd981..22e539f874f 100644
--- a/gradle/documentation/check-broken-links.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.documentation.check-broken-links.gradle
@@ -15,20 +15,22 @@
* limitations under the License.
*/
-def resources = scriptResources(buildscript)
+def resources = rootProject.file("gradle/documentation/check-broken-links")
configure(project(':lucene:documentation')) {
- task checkBrokenLinks(type: CheckBrokenLinksTask) {
- group 'Verification'
- description 'Check broken links in the entire documentation'
+ tasks.register("checkBrokenLinks", CheckBrokenLinksTask, {
+ group = 'Verification'
+ description = 'Check broken links in the entire documentation'
dependsOn 'documentation'
validationScript = file("${resources}/checkJavadocLinks.py")
docsDir.fileProvider(provider { -> file(project.docroot) })
output = project.file("${buildDir}/check-broken-links-output.txt")
- }
+ })
- check.dependsOn checkBrokenLinks
+ tasks.named("check").configure {
+ dependsOn "checkBrokenLinks"
+ }
}
@CacheableTask
diff --git a/gradle/documentation/documentation.gradle b/build-tools/build-infra/src/main/groovy/lucene.documentation.gradle
similarity index 53%
rename from gradle/documentation/documentation.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.documentation.gradle
index 9849d874ca1..87c67558d99 100644
--- a/gradle/documentation/documentation.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.documentation.gradle
@@ -15,69 +15,75 @@
* limitations under the License.
*/
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
configure(rootProject) {
- def urlVersion = project.baseVersion.replace('.', '_')
+ def urlVersion = rootProject.ext.baseVersion.replace('.', '_')
+
+ Provider<String> luceneJavadocUrl = buildOptions.addOption("lucene.javadoc.url",
+ "External Javadoc URL for documentation generator.", provider {
+ if (project.version != project.baseVersion) {
+ // non-release build does not cross-link between modules.
+ return null
+ } else {
+ // release build
+ return "https://lucene.apache.org/core/${urlVersion}"
+ }
+ })
ext {
- luceneDocUrl = project.propertyOrDefault('lucene.javadoc.url', {
- if (project.version != project.baseVersion) {
- // non-release build does not cross-link between modules.
- return null
- } else {
- // release build
- "https://lucene.apache.org/core/${urlVersion}"
- }
- }())
+ luceneDocUrl = luceneJavadocUrl.getOrElse(null)
}
- task documentation() {
+ def documentationTask = tasks.register("documentation", {
group = 'documentation'
description = 'Generate all documentation'
dependsOn ':lucene:documentation:assemble'
- }
+ })
- assemble.dependsOn documentation
+ assemble.dependsOn documentationTask
}
-// docroot will point to Lucene and Solr relative directory for each sub-project.
configure(project(':lucene:documentation')) {
ext {
- docroot = file("${buildDir}/site")
- docrootMinimal = file("${buildDir}/minimalSite")
+ docroot = layout.buildDirectory.dir("site").get().asFile
markdownSrc = file("src/markdown")
assets = file("src/assets")
}
- task documentation() {
+ def documentationTask = tasks.register("documentation", {
group = 'documentation'
description = "Generate ${project.name.capitalize()} documentation"
- dependsOn project.parent.subprojects.collect { prj ->
+ dependsOn project(":lucene").subprojects.collect { prj ->
prj.tasks.matching { it.name == 'renderSiteJavadoc' }
}
- dependsOn 'changesToHtml','copyDocumentationAssets',
- 'markdownToHtml','createDocumentationIndex'
- }
- task copyDocumentationAssets(type: Copy) {
+ dependsOn 'changesToHtml', 'copyDocumentationAssets',
+ 'markdownToHtml', 'createDocumentationIndex'
+ })
+
+ tasks.register("copyDocumentationAssets", Copy, {
includeEmptyDirs = false
- from(project.assets)
- into project.docroot
- }
-
+ from project.ext.assets
+ into project.ext.docroot
+ })
+
assemble {
- dependsOn documentation
+ dependsOn documentationTask
}
configurations {
site
}
-
+
artifacts {
- site project.docroot, {
- builtBy documentation
+ site project.ext.docroot, {
+ builtBy documentationTask
}
}
}
@@ -85,6 +91,5 @@ configure(project(':lucene:documentation')) {
configure(project(":lucene")) {
ext {
docroot = project('documentation').docroot
- docrootMinimal = project('documentation').docrootMinimal
}
}
diff --git a/gradle/documentation/markdown.gradle b/build-tools/build-infra/src/main/groovy/lucene.documentation.markdown.gradle
similarity index 83%
rename from gradle/documentation/markdown.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.documentation.markdown.gradle
index 1f9be37868e..c6c9ba44751 100644
--- a/gradle/documentation/markdown.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.documentation.markdown.gradle
@@ -28,46 +28,30 @@ import com.vladsch.flexmark.util.data.MutableDataSet;
import com.vladsch.flexmark.util.sequence.Escaping;
import groovy.text.SimpleTemplateEngine;
-buildscript {
- repositories {
- mavenCentral()
- }
-
- dependencies {
- classpath deps.flexmark.core
- classpath deps.flexmark.ext.abbreviation
- classpath deps.flexmark.ext.attributes
- classpath deps.flexmark.ext.autolink
- classpath deps.flexmark.ext.tables
- }
-}
-
configure(project(':lucene:documentation')) {
- task markdownToHtml(type: Copy) {
- dependsOn copyDocumentationAssets
-
- filteringCharset = 'UTF-8'
- includeEmptyDirs = false
- into project.docroot
- rename(/\.md$/, '.html')
- filter(MarkdownFilter)
- }
-}
+ tasks.register("markdownToHtml", Copy, {
+ dependsOn "copyDocumentationAssets"
-configure(project(':lucene:documentation')) {
- markdownToHtml {
from(project.parent.projectDir) {
include 'MIGRATE.md'
include 'JRE_VERSION_MIGRATION.md'
include 'SYSTEM_REQUIREMENTS.md'
}
- }
- task createDocumentationIndex(type: MarkdownTemplateTask) {
- dependsOn markdownToHtml
+ filteringCharset = 'UTF-8'
+ includeEmptyDirs = false
+
+ rename(/\.md$/, '.html')
+ filter(MarkdownFilter)
+
+ into project.ext.docroot
+ })
+
+ tasks.register("createDocumentationIndex", MarkdownTemplateTask, {
+ dependsOn "markdownToHtml"
- outputFile = file("${project.docroot}/index.html")
- templateFile = file("${project.markdownSrc}/index.template.md")
+ outputFile = file("${project.ext.docroot}/index.html")
+ templateFile = file("${project.ext.markdownSrc}/index.template.md")
def defaultCodecFile = project(':lucene:core').file('src/java/org/apache/lucene/codecs/Codec.java')
inputs.file(defaultCodecFile)
@@ -86,7 +70,7 @@ configure(project(':lucene:documentation')) {
})
withProjectList()
- }
+ })
}
// filter that can be used with the "copy" task of Gradle that transforms Markdown files
@@ -98,14 +82,14 @@ class MarkdownFilter extends FilterReader {
// converts it and provides result downstream as a StringReader
super(new StringReader(convert(reader.text)));
}
-
+
public static String convert(String markdownSource) {
// first replace LUCENE and SOLR issue numbers with a markdown link
markdownSource = markdownSource.replaceAll(/(?s)\b(LUCENE|SOLR)\-\d+\b/,
- '[$0](https://issues.apache.org/jira/browse/$0)');
+ '[$0](https://issues.apache.org/jira/browse/$0)');
markdownSource = markdownSource.replaceAll(/(?s)\b(GITHUB#|GH-)(\d+)\b/,
- '[$0](https://github.com/apache/lucene/issues/$2)');
-
+ '[$0](https://github.com/apache/lucene/issues/$2)');
+
// convert the markdown
MutableDataSet options = new MutableDataSet();
options.setFrom(ParserEmulationProfile.MARKDOWN);
@@ -120,12 +104,12 @@ class MarkdownFilter extends FilterReader {
Document parsed = Parser.builder(options).build().parse(markdownSource);
StringBuilder html = new StringBuilder('<html>\n<head>\n');
- CharSequence title = parsed.getFirstChildAny(Heading.class)?.getText();
+ CharSequence title = parsed.getFirstChildAny(Heading.class)?.getText();
if (title != null) {
html.append('<title>').append(Escaping.escapeHtml(title, false)).append('</title>\n');
}
html.append('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n')
- .append('</head>\n<body>\n');
+ .append('</head>\n<body>\n');
HtmlRenderer.builder(options).build().render(parsed, html);
html.append('</body>\n</html>\n');
return html;
@@ -144,19 +128,21 @@ class MarkdownTemplateTask extends DefaultTask {
@OutputFile
File outputFile
-
+
@Input
@Optional
final MapProperty<String,Object> binding = project.objects.mapProperty(String, Object)
-
+
/** adds a property "projectList" containing all subprojects with javadocs as markdown bullet list */
void withProjectList() {
binding.put('projectList', project.providers.provider{
def projects = productProject.subprojects.findAll{ it.tasks.findByName('renderSiteJavadoc')?.enabled }
- .sort(false, Comparator.comparing{ (it.name != 'core') as Boolean }
- .thenComparing(Comparator.comparing{ (it.name != 'solrj') as Boolean })
- .thenComparing(Comparator.comparing{ (it.name == 'test-framework') as Boolean })
- .thenComparing(Comparator.comparing{ it.path }));
+ .sort(false, Comparator.comparing{
+ (it.name != 'core') as Boolean
+ }
+ .thenComparing(Comparator.comparing{ (it.name != 'solrj') as Boolean })
+ .thenComparing(Comparator.comparing{ (it.name == 'test-framework') as Boolean })
+ .thenComparing(Comparator.comparing{ it.path }));
return projects.collect{ project ->
def text = "**[${project.relativeDocPath.replace('/','-')}](${project.relativeDocPath}/index.html):** ${project.description}"
if (project.name == 'core') {
diff --git a/gradle/documentation/render-javadoc.gradle b/build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradle
similarity index 62%
rename from gradle/documentation/render-javadoc.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradle
index a161fbc24dd..5f72485a42f 100644
--- a/gradle/documentation/render-javadoc.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradle
@@ -20,42 +20,42 @@ import org.gradle.internal.jvm.Jvm
// generate javadocs by calling javadoc tool
// see https://docs.oracle.com/en/java/javase/11/tools/javadoc.html
-def resources = scriptResources(buildscript)
+def resources = rootProject.file("gradle/documentation/render-javadoc")
allprojects {
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
configurations {
missingdoclet
}
dependencies {
- missingdoclet "org.apache.lucene.tools:missing-doclet"
+ missingdoclet project(":lucene:build-tools:missing-doclet")
}
project.ext {
relativeDocPath = project.path.replaceFirst(/:\w+:/, "").replace(':', '/')
}
- // We disable the default javadoc task and have our own
- // javadoc rendering task below. The default javadoc task
- // will just invoke 'renderJavadoc' (to allow people to call
- // conventional task name).
- tasks.matching { it.name == "javadoc" }.all {
- enabled = false
- dependsOn "renderJavadoc"
- }
-
- task renderJavadoc(type: RenderJavadocTask) {
- description "Generates Javadoc API documentation for each module. This directly invokes javadoc tool."
- group "documentation"
+ def renderJavadoc = tasks.register("renderJavadoc", RenderJavadocTask, {
+ description = "Generates Javadoc API documentation for each module. This directly invokes javadoc tool."
+ group = "documentation"
taskResources = resources
dependsOn sourceSets.main.compileClasspath
classpath = sourceSets.main.compileClasspath
srcDirSet = sourceSets.main.java
- releaseVersion = rootProject.minJavaVersion
+ releaseVersion = rootProject.ext.minJavaVersion
- outputDir = project.javadoc.destinationDir
+ outputDir = project.tasks.named("javadoc").get().destinationDir
+ })
+
+ // We disable the default javadoc task and have our own
+ // javadoc rendering task below. The default javadoc task
+ // will just invoke 'renderJavadoc' (to allow people to call
+ // conventional task name).
+ tasks.named("javadoc").configure {
+ enabled = false
+ dependsOn renderJavadoc
}
if (project.path == ':lucene:luke' || !(project in rootProject.ext.mavenProjects)) {
@@ -63,17 +63,19 @@ allprojects {
// as part of the site's creation. A side-effect of this is that javadocs would not
// be linted for these projects. To avoid this, we connect the regular javadoc task
// to check so that everything is validated.
- project.tasks.getByName("check").dependsOn renderJavadoc
+ project.tasks.named("check").configure {
+ dependsOn renderJavadoc
+ }
} else {
- task renderSiteJavadoc(type: RenderJavadocTask) {
- description "Generates Javadoc API documentation for the site (relative links)."
- group "documentation"
+ tasks.register("renderSiteJavadoc", RenderJavadocTask, {
+ description = "Generates Javadoc API documentation for the site (relative links)."
+ group = "documentation"
taskResources = resources
dependsOn sourceSets.main.compileClasspath
classpath = sourceSets.main.compileClasspath
srcDirSet = sourceSets.main.java
- releaseVersion = rootProject.minJavaVersion
+ releaseVersion = rootProject.ext.minJavaVersion
relativeProjectLinks = true
@@ -81,8 +83,8 @@ allprojects {
// Place the documentation under the documentation directory.
// docroot is defined in 'documentation.gradle'
- outputDir = project.docroot.toPath().resolve(project.relativeDocPath).toFile()
- }
+ outputDir = project.docroot.toPath().resolve(project.ext.relativeDocPath).toFile()
+ })
}
}
}
@@ -90,15 +92,29 @@ allprojects {
// Set up titles and link up some offline docs for all documentation
// (they may be unused but this doesn't do any harm).
-def javaJavadocPackages = rootProject.file("${resources}/java21/")
-def junitJavadocPackages = rootProject.file("${resources}/junit/")
+def minJava = deps.versions.minJava.get()
+def javaJavadocPackages = rootProject.file("${resources}/java-${minJava}/")
+if (!javaJavadocPackages.exists()) {
+ throw new GradleException("Prefetched javadoc element-list is missing at " + javaJavadocPackages + ", " +
+ "create this directory and fetch the element-list file from " +
+ "from https://docs.oracle.com/en/java/javase/${minJava}/docs/api/element-list")
+}
+
+def junitVersion = deps.versions.junit.get()
+def junitJavadocPackages = rootProject.file("${resources}/junit-${junitVersion}/")
+if (!junitJavadocPackages.exists()) {
+ throw new GradleException("Prefetched javadoc package-list is missing at " + junitJavadocPackages + ", " +
+ "create this directory and fetch the package-list file from " +
+ "from https://junit.org/junit4/javadoc/${junitVersion}/package-list")
+}
+
allprojects {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
title = "Lucene ${project.version} ${project.name} API"
offlineLinks += [
- "https://docs.oracle.com/en/java/javase/21/docs/api/": javaJavadocPackages,
- "https://junit.org/junit4/javadoc/4.12/": junitJavadocPackages
+ ("https://docs.oracle.com/en/java/javase/${minJava}/docs/api/".toString()): javaJavadocPackages,
+ ("https://junit.org/junit4/javadoc/${junitVersion}/".toString()): junitJavadocPackages
]
luceneDocUrl = provider({ rootProject.luceneDocUrl })
@@ -111,114 +127,114 @@ allprojects {
// Configure project-specific tweaks and to-dos.
configure(project(":lucene:analysis:common")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
}
}
configure([
- project(":lucene:analysis:kuromoji"),
- project(":lucene:analysis:nori"),
- project(":lucene:analysis:opennlp"),
- project(":lucene:analysis:smartcn"),
- project(":lucene:benchmark"),
- project(":lucene:codecs"),
- project(":lucene:grouping"),
- project(":lucene:highlighter"),
- project(":lucene:luke"),
- project(":lucene:monitor"),
- project(":lucene:queries"),
- project(":lucene:queryparser"),
- project(":lucene:replicator"),
- project(":lucene:spatial-extras"),
+ project(":lucene:analysis:kuromoji"),
+ project(":lucene:analysis:nori"),
+ project(":lucene:analysis:opennlp"),
+ project(":lucene:analysis:smartcn"),
+ project(":lucene:benchmark"),
+ project(":lucene:codecs"),
+ project(":lucene:grouping"),
+ project(":lucene:highlighter"),
+ project(":lucene:luke"),
+ project(":lucene:monitor"),
+ project(":lucene:queries"),
+ project(":lucene:queryparser"),
+ project(":lucene:replicator"),
+ project(":lucene:spatial-extras"),
]) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
}
}
configure([
- project(":lucene:analysis:icu"),
- project(":lucene:analysis:morfologik"),
- project(":lucene:analysis:phonetic"),
- project(":lucene:analysis:stempel"),
- project(":lucene:classification"),
- project(":lucene:demo"),
- project(":lucene:expressions"),
- project(":lucene:facet"),
- project(":lucene:join"),
- project(":lucene:spatial3d"),
- project(":lucene:suggest"),
+ project(":lucene:analysis:icu"),
+ project(":lucene:analysis:morfologik"),
+ project(":lucene:analysis:phonetic"),
+ project(":lucene:analysis:stempel"),
+ project(":lucene:classification"),
+ project(":lucene:demo"),
+ project(":lucene:expressions"),
+ project(":lucene:facet"),
+ project(":lucene:join"),
+ project(":lucene:spatial3d"),
+ project(":lucene:suggest"),
]) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing @param tags
javadocMissingLevel = "method"
}
}
configure(project(":lucene:backward-codecs")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing @param tags
javadocMissingLevel = "method"
}
}
configure(project(":lucene:test-framework")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
}
}
configure(project(":lucene:sandbox")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
}
}
configure(project(":lucene:spatial-test-fixtures")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
}
}
configure(project(":lucene:misc")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
}
}
configure(project(":lucene:core")) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// TODO: fix missing javadocs
javadocMissingLevel = "class"
// some packages are fixed already
javadocMissingMethod = [
- "org.apache.lucene.util.automaton",
- "org.apache.lucene.analysis.standard",
- "org.apache.lucene.analysis.tokenattributes",
- "org.apache.lucene.document",
- "org.apache.lucene.search.similarities",
- "org.apache.lucene.index",
- "org.apache.lucene.codecs",
- "org.apache.lucene.codecs.lucene50",
- "org.apache.lucene.codecs.lucene60",
- "org.apache.lucene.codecs.lucene80",
- "org.apache.lucene.codecs.lucene84",
- "org.apache.lucene.codecs.lucene86",
- "org.apache.lucene.codecs.lucene87",
- "org.apache.lucene.codecs.perfield"
+ "org.apache.lucene.util.automaton",
+ "org.apache.lucene.analysis.standard",
+ "org.apache.lucene.analysis.tokenattributes",
+ "org.apache.lucene.document",
+ "org.apache.lucene.search.similarities",
+ "org.apache.lucene.index",
+ "org.apache.lucene.codecs",
+ "org.apache.lucene.codecs.lucene50",
+ "org.apache.lucene.codecs.lucene60",
+ "org.apache.lucene.codecs.lucene80",
+ "org.apache.lucene.codecs.lucene84",
+ "org.apache.lucene.codecs.lucene86",
+ "org.apache.lucene.codecs.lucene87",
+ "org.apache.lucene.codecs.perfield"
]
}
}
configure(project(':lucene:demo')) {
- project.tasks.withType(RenderJavadocTask) {
+ project.tasks.withType(RenderJavadocTask).configureEach {
// For the demo, we link the example source in the javadocs, as it's ref'ed elsewhere
linksource = true
}
@@ -228,11 +244,10 @@ configure(project(':lucene:demo')) {
// - each RenderJavaDocs task gets a dependency to all tasks with the same name in its dependencies
// - the dependency is using dependsOn with a closure to enable lazy evaluation
configure(subprojects) {
- project.tasks.withType(RenderJavadocTask) { task ->
+ project.tasks.withType(RenderJavadocTask).configureEach { task ->
task.dependsOn {
task.project.configurations.implementation.allDependencies.withType(ProjectDependency).collect { dep ->
- def otherProject = dep.dependencyProject
- return otherProject.tasks.findByName(task.name)
+ return dep.path + ":" + task.name
}
}
}
@@ -260,7 +275,7 @@ class RenderJavadocTask extends DefaultTask {
@IgnoreEmptyDirectories
@SkipWhenEmpty
SourceDirectorySet srcDirSet;
-
+
@OutputDirectory
File outputDir
@@ -317,7 +332,7 @@ class RenderJavadocTask extends DefaultTask {
@Optional
@Input
final Property<String> executable = project.objects.property(String).convention(
- project.provider { Jvm.current().javadocExecutable.toString() })
+ project.provider { Jvm.current().javadocExecutable.toString() })
@InputDirectory
@PathSensitive(PathSensitivity.RELATIVE)
@@ -328,10 +343,12 @@ class RenderJavadocTask extends DefaultTask {
private Set findRenderTasksInDependencies() {
Set found = []
def collectDeps
- collectDeps = { task -> task.taskDependencies.getDependencies(task).findAll{ it.name == this.name && it.enabled && !found.contains(it) }.each{
- found << it
- collectDeps(it)
- }}
+ collectDeps = { task ->
+ project.gradle.taskGraph.getDependencies(task).findAll{ it.name == this.name && it.enabled && !found.contains(it) }.each{
+ found << it
+ collectDeps(it)
+ }
+ }
collectDeps(this)
return found
}
@@ -341,20 +358,29 @@ class RenderJavadocTask extends DefaultTask {
def srcDirs = srcDirSet.sourceDirectories.filter { dir -> dir.exists() }
def optionsFile = project.file("${getTemporaryDir()}/javadoc-options.txt")
-
+
// create the directory, so relative link calculation knows that it's a directory:
outputDir.mkdirs();
-
+
def opts = []
- def overviewSourceSetDir = srcDirs.filter { dir -> project.file("${dir}/overview.html").exists() }.singleFile
- opts << [ '-overview', project.file("${overviewSourceSetDir}/overview.html") ]
+ def overviewFiles = srcDirs
+ .collect { dir -> project.file("${dir}/overview.html") }
+ .findAll { overviewFile -> overviewFile.exists() }
+
+ if (!overviewFiles.isEmpty()) {
+ assert overviewFiles.size() == 1 : "More than one overview file?: " + overviewFiles
+ opts << [
+ '-overview',
+ project.file("${overviewFiles.getFirst()}/overview.html")
+ ]
+ }
- opts << [ '-d', outputDir ]
+ opts << ['-d', outputDir]
opts << '-protected'
- opts << [ '-encoding', 'UTF-8' ]
- opts << [ '-charset', 'UTF-8' ]
- opts << [ '-docencoding', 'UTF-8' ]
+ opts << ['-encoding', 'UTF-8']
+ opts << ['-charset', 'UTF-8']
+ opts << ['-docencoding', 'UTF-8']
if (!enableSearch) {
opts << '-noindex'
}
@@ -364,29 +390,59 @@ class RenderJavadocTask extends DefaultTask {
opts << '-linksource'
}
opts << '-use'
- opts << [ '-locale', 'en_US' ]
- opts << [ '-windowtitle', title ]
- opts << [ '-doctitle', title ]
+ opts << ['-locale', 'en_US']
+ opts << ['-windowtitle', title]
+ opts << ['-doctitle', title]
if (!classpath.isEmpty()) {
- opts << [ '-classpath', classpath.asPath ]
+ opts << [
+ '-classpath',
+ classpath.asPath
+ ]
}
- opts << [ '-bottom', "<i>Copyright &copy; 2000-${project.buildYear} Apache Software Foundation. All Rights Reserved.</i>" ]
+ opts << [
+ '-bottom',
+ "<i>Copyright &copy; 2000-${project.buildYear} Apache Software Foundation. All Rights Reserved.</i>"
+ ]
- opts << [ '-tag', 'lucene.experimental:a:WARNING: This API is experimental and might change in incompatible ways in the next release.' ]
- opts << [ '-tag', 'lucene.internal:a:NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.' ]
- opts << [ '-tag', "lucene.spi:t:SPI Name (case-insensitive: if the name is 'htmlStrip', 'htmlstrip' can be used when looking up the service)." ]
+ opts << [
+ '-tag',
+ 'lucene.experimental:a:WARNING: This API is experimental and might change in incompatible ways in the next release.'
+ ]
+ opts << [
+ '-tag',
+ 'lucene.internal:a:NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.'
+ ]
+ opts << [
+ '-tag',
+ "lucene.spi:t:SPI Name (case-insensitive: if the name is 'htmlStrip', 'htmlstrip' can be used when looking up the service)."
+ ]
- opts << [ '-doclet', "org.apache.lucene.missingdoclet.MissingDoclet" ]
- opts << [ '-docletpath', docletpath.asPath ]
- opts << [ '--missing-level', javadocMissingLevel ]
+ opts << [
+ '-doclet',
+ "org.apache.lucene.missingdoclet.MissingDoclet"
+ ]
+ opts << [
+ '-docletpath',
+ docletpath.asPath
+ ]
+ opts << [
+ '--missing-level',
+ javadocMissingLevel
+ ]
if (javadocMissingIgnore) {
- opts << [ '--missing-ignore', String.join(',', javadocMissingIgnore) ]
+ opts << [
+ '--missing-ignore',
+ String.join(',', javadocMissingIgnore)
+ ]
}
if (javadocMissingMethod) {
- opts << [ '--missing-method', String.join(',', javadocMissingMethod) ]
+ opts << [
+ '--missing-method',
+ String.join(',', javadocMissingMethod)
+ ]
}
- opts << [ '-quiet' ]
+ opts << ['-quiet']
// Add all extra options, if any.
opts.addAll(extraOpts.orElse([]).get())
@@ -425,16 +481,22 @@ class RenderJavadocTask extends DefaultTask {
throw new GradleException("Expected pre-rendered package-list or element-list at ${dir}.")
}
logger.info("Linking ${url} to ${dir}")
- opts << [ '-linkoffline', url, dir ]
+ opts << ['-linkoffline', url, dir]
}
- opts << [ '--release', releaseVersion.toString() ]
+ opts << [
+ '--release',
+ releaseVersion.toString()
+ ]
opts << '-Xdoclint:all,-missing'
// Increase Javadoc's heap.
- opts += [ "-J-Xmx512m" ]
+ opts += ["-J-Xmx512m"]
// Force locale to be "en_US" (fix for: https://bugs.openjdk.java.net/browse/JDK-8222793)
- opts += [ "-J-Duser.language=en", "-J-Duser.country=US" ]
+ opts += [
+ "-J-Duser.language=en",
+ "-J-Duser.country=US"
+ ]
// -J options have to be passed on command line, they are not interpreted if passed via args file.
def jOpts = opts.findAll { opt -> opt instanceof String && opt.startsWith("-J") }
@@ -444,8 +506,10 @@ class RenderJavadocTask extends DefaultTask {
opts.addAll(
srcDirs.collectMany { dir ->
project.fileTree(dir: dir, include: "**/*.java", exclude: "**/module-info.java").files
- }.collect { it.toString() }
- )
+ }.collect {
+ it.toString()
+ }
+ )
// handle doc-files manually since in explicit source file mode javadoc does not copy them.
srcDirs.each { File dir ->
@@ -477,18 +541,20 @@ class RenderJavadocTask extends DefaultTask {
logger.info("Javadoc executable used: ${javadocCmd}")
project.quietExec {
- executable javadocCmd
+ executable javadocCmd
- args += [ "@${optionsFile}" ]
- args += jOpts
+ args += ["@${optionsFile}"]
+ args += jOpts
}
// append some special table css, prettify css
ant.concat(destfile: "${outputDir}/stylesheet.css", append: "true", fixlastline: "true", encoding: "UTF-8") {
filelist(dir: taskResources, files:
- ["table_padding.css",
- "custom_styles.css",
- "prettify/prettify.css"].join(" ")
+ [
+ "table_padding.css",
+ "custom_styles.css",
+ "prettify/prettify.css"
+ ].join(" ")
)
}
diff --git a/gradle/hacks/downloader-retries.gradle b/build-tools/build-infra/src/main/groovy/lucene.hacks.downloader-retries.gradle
similarity index 67%
rename from gradle/hacks/downloader-retries.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.hacks.downloader-retries.gradle
index 84876d287c5..5dd4ab9cdc3 100644
--- a/gradle/hacks/downloader-retries.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.hacks.downloader-retries.gradle
@@ -15,13 +15,16 @@
* limitations under the License.
*/
+import de.undercouch.gradle.tasks.download.DownloadTaskPlugin
+import de.undercouch.gradle.tasks.download.Download
+
+// Configures the Download task to retry on temporary network glitches.
+
allprojects {project ->
- // Limit configuration to just those projects that actually have the plugin enabled.
- plugins.matching { Plugin plugin ->
- return plugin.class.name == "de.undercouch.gradle.tasks.download.DownloadTaskPlugin"
- }.configureEach {
- project.tasks.withType(Download).configureEach {
- it.retries 3
- }
+ // Limit configuration to just those projects that actually have the plugin enabled.
+ plugins.withType(DownloadTaskPlugin).configureEach {
+ project.tasks.withType(Download).configureEach {
+ it.retries 3
}
-}
\ No newline at end of file
+ }
+}
diff --git a/gradle/hacks/dummy-outputs.gradle b/build-tools/build-infra/src/main/groovy/lucene.hacks.dummy-outputs.gradle
similarity index 68%
rename from gradle/hacks/dummy-outputs.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.hacks.dummy-outputs.gradle
index 1d9a1541a05..9c8fa0efc39 100644
--- a/gradle/hacks/dummy-outputs.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.hacks.dummy-outputs.gradle
@@ -15,27 +15,28 @@
* limitations under the License.
*/
+import java.nio.file.Files
+
// LUCENE-9505: utility function that sets up dummy outputs for a task so that
// clean[TaskName] works and allows selective re-runs.
-def setupDummyOutputs = { Task task ->
- File dummyOutput = file("${task.project.buildDir}/tasks/${task.name}/dummy-output.txt")
- task.outputs.file(dummyOutput)
- task.doLast {
- if (!dummyOutput.exists()) {
- dummyOutput.createNewFile()
- }
- }
-}
-
allprojects {
tasks.matching {
it.name.startsWith("ecjLint") ||
- it.name in [
- "gradlewScriptsTweaked",
- "validateSourcePatterns"
- ] }.all { Task task ->
- task.logger.info("Setting up ${task.path} as no-output.")
- setupDummyOutputs(task)
+ it.name in [
+ "gradlewScriptsTweaked",
+ "validateSourcePatterns"
+ ]
+ }.configureEach { Task task ->
+ task.logger.info("Adding a dummy-output to ${task.path}.")
+
+ 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())
+ }
+ }
}
}
diff --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.gradle
new file mode 100644
index 00000000000..da4f717e8e8
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.hacks.turbocharge-jvm-opts.gradle
@@ -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.
+ */
+
+// 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.hacks.wipe-gradle-temp.gradle b/build-tools/build-infra/src/main/groovy/lucene.hacks.wipe-gradle-temp.gradle
new file mode 100644
index 00000000000..c9db9b07e3e
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.hacks.wipe-gradle-temp.gradle
@@ -0,0 +1,76 @@
+/*
+ * 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.file.Files
+import java.time.temporal.ChronoUnit
+import java.time.Instant
+import java.util.stream.Stream
+
+// See LUCENE-9471. We redirect temporary location for gradle
+// so that it doesn't pollute user's tmp. Wipe it during a clean though.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+gradle.buildFinished {
+ // we clean up the java.io.tmpdir we've redirected gradle to use (LUCENE-9471).
+ // these are still used and populated with junk.
+ rootProject.delete fileTree(".gradle/tmp").matching {
+ include "gradle-worker-classpath*"
+ }
+
+ // clean up any files older than 3 hours from the user's gradle temp. the time
+ // limit is added so that we don't interfere with any concurrent builds... just in case.
+ Instant deadline = Instant.now().minus(3, ChronoUnit.HOURS);
+ List<Stream<java.nio.file.Path>> toDelete = new ArrayList<>()
+
+ def gradleTmp = gradle.gradleUserHomeDir.toPath().resolve(".tmp")
+ if (Files.exists(gradleTmp)) {
+ toDelete.add(Files.list(gradleTmp))
+ }
+ def daemonDir = gradle.gradleUserHomeDir.toPath().resolve("daemon").resolve("${gradle.gradleVersion}")
+ if (Files.exists(daemonDir)) {
+ toDelete.add(Files.list(daemonDir).filter {path -> path.toString().endsWith(".out.log") })
+ }
+
+ toDelete.each {
+ it.withCloseable {stream ->
+ stream.filter { p -> Files.isRegularFile(p) }
+ .filter { p -> Files.getLastModifiedTime(p).toInstant().isBefore(deadline) }
+ .forEach { p ->
+ Files.deleteIfExists(p)
+ }
+ }
+ }
+}
+
+// Make sure we clean up after running tests.
+allprojects {
+ plugins.withType(JavaPlugin).configureEach {
+ def wipeTaskTempTask = tasks.register("wipeTaskTemp", Delete, {
+ delete tasks.withType(Test).collect {
+ fileTree(it.temporaryDir, {
+ include "jar_extract*"
+ })
+ }
+ })
+
+ tasks.withType(Test).configureEach {
+ finalizedBy wipeTaskTempTask
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.help.gradle b/build-tools/build-infra/src/main/groovy/lucene.help.gradle
new file mode 100644
index 00000000000..b93fe908728
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.help.gradle
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+
+// Add "help" tasks which display plain text files under 'help' folder.
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+def helpFiles = [
+ [
+ "Workflow",
+ "help/workflow.txt",
+ "Typical workflow commands."
+ ],
+ [
+ "Tests",
+ "help/tests.txt",
+ "Tests, filtering, beasting, etc."
+ ],
+ [
+ "Formatting",
+ "help/formatting.txt",
+ "Code formatting conventions."
+ ],
+ [
+ "Jvms",
+ "help/jvms.txt",
+ "Using alternative or EA JVM toolchains."
+ ],
+ [
+ "Deps",
+ "help/dependencies.txt",
+ "Declaring, inspecting and excluding dependencies."
+ ],
+ [
+ "ForbiddenApis",
+ "help/forbiddenApis.txt",
+ "How to add/apply rules for forbidden APIs."
+ ],
+ [
+ "LocalSettings",
+ "help/localSettings.txt",
+ "Local settings, overrides and build performance tweaks."
+ ],
+ [
+ "Regeneration",
+ "help/regeneration.txt",
+ "How to refresh generated and derived resources."
+ ],
+ [
+ "Jmh",
+ "help/jmh.txt",
+ "JMH micro-benchmarks."
+ ],
+ [
+ "Git",
+ "help/git.txt",
+ "Git assistance and guides."
+ ],
+ [
+ "IDEs",
+ "help/IDEs.txt",
+ "IDE support."
+ ],
+ [
+ "Publishing",
+ "help/publishing.txt",
+ "Maven and other artifact publishing, signing, etc."
+ ],
+]
+
+// Declare helpXyz task to display the given help section.
+helpFiles.each { section, path, sectionInfo ->
+ tasks.register("help${section}", {
+ group = 'Help (developer guides and hints)'
+ description = sectionInfo
+ doFirst {
+ println "\n" + rootProject.file(path).getText("UTF-8")
+ }
+ })
+}
+
+// Add custom section to the default 'help' task.
+tasks.named("help").configure {
+ doFirst {
+ println ""
+ println "This is Lucene ${rootProject.version} build file (gradle ${gradle.gradleVersion}). See some guidelines in files"
+ println "found under the help/* folder or type any of these:"
+ println ""
+
+ helpFiles.each { section, path, sectionInfo ->
+ println String.format(Locale.ROOT,
+ " gradlew :help%-16s # %s", section, sectionInfo)
+ }
+
+ println ""
+ println "For the impatient, build the project with 'gradlew assemble', run all tests with 'gradlew check'."
+ throw new StopExecutionException()
+ }
+}
+
+// Make sure all help files exist.
+def allHelpFilesExist = tasks.register("allHelpFilesExist", {
+ doFirst {
+ helpFiles.each { section, path, sectionInfo ->
+ if (!rootProject.file(path).exists()) {
+ throw new GradleException("Help file missing: ${path} (correct help.gradle)")
+ }
+ }
+ }
+})
+
+tasks.named("check").configure {
+ dependsOn allHelpFilesExist
+}
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
new file mode 100644
index 00000000000..939ea285118
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.ide.eclipse.gradle
@@ -0,0 +1,153 @@
+/*
+ * 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 eclipseJavaVersion = eclipseJavaVersionOption.get()
+ def relativize = { File other -> rootProject.rootDir.relativePath(other).toString() }
+
+ eclipse {
+ project {
+ name = "Apache Lucene ${version}"
+ }
+
+ classpath {
+ defaultOutputDir = file('build/eclipse')
+
+ file {
+ beforeMerged { classpath ->
+ classpath.entries.removeAll {
+ it.kind == "src"
+ }
+ }
+
+ whenMerged { classpath ->
+ 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 = []
+ Set<File> jars = []
+ 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) }
+ }
+ }
+
+ // This is hacky - we take the resolved compile classpath and just
+ // include JAR files from there. We should probably make it smarter
+ // by looking at real dependencies. But then: this Eclipse configuration
+ // doesn't really separate sources anyway so why bother.
+ jars += prj.configurations.compileClasspath.resolve()
+ jars += prj.configurations.testCompileClasspath.resolve()
+ }
+
+ classpath.entries += sources.sort().collect { name ->
+ def sourceFolder = new SourceFolder(name, "build/eclipse/" + name)
+ sourceFolder.setExcludes(["module-info.java"])
+ return sourceFolder
+ }
+ classpath.entries += jars.unique().findAll { location -> location.isFile() && !(location.name ==~ /lucene-.*\.jar/) }.collect { location ->
+ new LibEntry(location.toString())
+ }
+ }
+ }
+ }
+
+ 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)
+ }
+}
+
+public class LibEntry implements ClasspathEntry {
+ private String path;
+
+ LibEntry(String path) {
+ this.path = path;
+ }
+
+ @Override
+ String getKind() {
+ return "lib"
+ }
+
+ @Override
+ void appendNode(Node node) {
+ node.appendNode("classpathentry", Map.of(
+ "kind", "lib",
+ "path", path
+ ))
+ }
+}
diff --git a/gradle/ide/intellij-idea.gradle b/build-tools/build-infra/src/main/groovy/lucene.ide.intellij-idea.gradle
similarity index 59%
rename from gradle/ide/intellij-idea.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.ide.intellij-idea.gradle
index cfb0d52fec1..3ca81b61560 100644
--- a/gradle/ide/intellij-idea.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.ide.intellij-idea.gradle
@@ -15,13 +15,13 @@
* limitations under the License.
*/
-// Try to detect IntelliJ model loader project structure "sync"
-//
-rootProject.ext.isIdea = Boolean.parseBoolean(System.getProperty("idea.active", "false"))
-rootProject.ext.isIdeaSync = Boolean.parseBoolean(System.getProperty("idea.sync.active", "false"))
-rootProject.ext.isIdeaBuild = (isIdea && !isIdeaSync)
+// Tweak settings to allow easier working with IntelliJ Idea
-if (isIdea) {
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+if (rootProject.ext.isIdea) {
logger.warn("IntelliJ Idea IDE detected.")
allprojects {
@@ -37,12 +37,12 @@ if (isIdea) {
}
}
-if (isIdeaSync) {
+if (rootProject.ext.isIdeaSync) {
allprojects {
// disable all MR-JAR folders by hiding them from IDE after evaluation:
- plugins.withType(JavaPlugin) {
- sourceSets.matching{ it.name ==~ /main\d+/ }.all{ SourceSet sourceSet ->
- project.afterEvaluate {
+ 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 = []
@@ -52,24 +52,17 @@ if (isIdeaSync) {
}
}
-if (isIdeaBuild) {
+if (rootProject.ext.isIdeaBuild) {
// Skip certain long tasks that are dependencies
// of 'assemble' if we're building from within IntelliJ.
- gradle.taskGraph.whenReady { taskGraph ->
- def tasks = taskGraph.getAllTasks()
-
- def skipTasks = [
- // Skip site javadoc rendering
- ".*:(renderSiteJavadoc)",
- ]
-
- logger.lifecycle("Skipping certain tasks on IntelliJ builds")
- tasks.each { task ->
- def taskPath = task.path
- if (skipTasks.any { pattern -> taskPath ==~ pattern }) {
- logger.debug("Skipping task on IntelliJ: " + taskPath)
- task.enabled = false
- }
- }
+ 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/lucene/distribution/artifact-signing.gradle b/build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle
similarity index 61%
rename from lucene/distribution/artifact-signing.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle
index 02eb775000f..955a4bb7501 100644
--- a/lucene/distribution/artifact-signing.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle
@@ -15,15 +15,20 @@
* limitations under the License.
*/
-// Configure release artifact signing.
+allprojects { project ->
+ if (['src/java', 'src/test'].any {path ->
+ project.file(path).exists()
+ }) {
+ plugins.apply("java-library")
-task signReleaseArchives(type: Sign) {
- dependsOn tasks.assembleBinaryTgz
- sign tasks.assembleBinaryTgz
-
- // The source tgz is not an archive task so be explicit about the outputs to sign.
- dependsOn tasks.assembleSourceTgz
- sign tasks.assembleSourceTgz.destination
-}
+ plugins.apply("lucene.java.folder-layout")
+ plugins.apply("lucene.java.javac")
+ plugins.apply("lucene.java.jar-manifest")
+ plugins.apply("lucene.java.tests-and-randomization")
+ plugins.apply("lucene.java.per-project-test-summary")
+ plugins.apply("lucene.validation.forbidden-apis")
+ plugins.apply("lucene.validation.ecj-lint")
+ }
+}
diff --git a/gradle/testing/alternative-jdk-support.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.alternative-jdk-support.gradle
similarity index 56%
rename from gradle/testing/alternative-jdk-support.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.alternative-jdk-support.gradle
index 4b421e1decf..888b8ea4ade 100644
--- a/gradle/testing/alternative-jdk-support.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.alternative-jdk-support.gradle
@@ -1,10 +1,3 @@
-
-import org.gradle.internal.jvm.JavaInfo
-import org.gradle.internal.jvm.Jvm
-import org.gradle.internal.jvm.inspection.JvmInstallationMetadata
-import org.gradle.internal.jvm.inspection.JvmMetadataDetector
-import org.gradle.jvm.toolchain.internal.InstallationLocation
-
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -22,21 +15,36 @@ import org.gradle.jvm.toolchain.internal.InstallationLocation
* limitations under the License.
*/
+import org.gradle.internal.jvm.JavaInfo
+import org.gradle.internal.jvm.Jvm
+import org.gradle.internal.jvm.inspection.JvmInstallationMetadata
+import org.gradle.internal.jvm.inspection.JvmMetadataDetector
+import org.gradle.jvm.toolchain.internal.InstallationLocation
+
// This adds support for compiling and testing against a different Java runtime.
//
// I failed to set it up leveraging Gradle's toolchains because
// a toolchain spec is not flexible enough to provide an exact location of the JVM to be used;
// if you have two identical JVM lang. versions in auto-discovered JVMs, an arbitrary one is used (?).
// This situation is not uncommon when debugging low-level stuff (hand-compiled JVM binaries).
-//
-// The code below is a workaround using internal gradle classes. It may stop working in the future
-// but for now it's fine.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+Provider<DirectoryProperty> runtimeJavaHomeOption =
+ buildOptions.addDirOption("runtime.java.home", "Home directory path to an alternative compilation/ runtime JDK.")
+
+// we used to have "RUNTIME_JAVA_HOME" uppercase env variable support so keep this option too.
+Provider<DirectoryProperty> legacyUpperCase = project.layout.projectDirectory.dir(
+ providers.environmentVariable("RUNTIME_JAVA_HOME")
+ )
+runtimeJavaHomeOption = runtimeJavaHomeOption.orElse(legacyUpperCase)
JavaInfo jvmGradle = Jvm.current();
JavaInfo jvmCurrent = {
- def runtimeJavaHome = propertyOrDefault("runtime.java.home", System.getenv('RUNTIME_JAVA_HOME'))
- if (runtimeJavaHome != null) {
- return Jvm.forHome(file(runtimeJavaHome))
+ if (runtimeJavaHomeOption.isPresent()) {
+ return Jvm.forHome(runtimeJavaHomeOption.get().asFile)
} else {
return jvmGradle
}
@@ -46,9 +54,8 @@ JvmMetadataDetector jvmDetector = project.services.get(JvmMetadataDetector)
if (jvmGradle != jvmCurrent) {
configure(rootProject) {
- task altJvmWarning() {
+ tasks.register("altJvmWarning", {
doFirst {
-
def jvmInfo = { JavaInfo javaInfo ->
JvmInstallationMetadata jvmMetadata = jvmDetector.getMetadata(InstallationLocation.userDefined(javaInfo.javaHome, "specific path"))
return "${jvmMetadata.languageVersion} (${jvmMetadata.displayName} ${jvmMetadata.runtimeVersion}, home at: ${jvmMetadata.javaHome})"
@@ -59,35 +66,38 @@ if (jvmGradle != jvmCurrent) {
Gradle runs with ${jvmInfo(jvmGradle)}
""")
}
- }
+ })
}
allprojects {
- // Any tests
- tasks.withType(Test) {
- dependsOn ":altJvmWarning"
- executable = jvmCurrent.javaExecutable
- }
+ plugins.withType(JavaPlugin).configureEach {
+ // Any tests
+ tasks.withType(Test).configureEach {
+ dependsOn ":altJvmWarning"
+ executable = jvmCurrent.javaExecutable
+ }
- // Any javac compilation tasks
- tasks.withType(JavaCompile) {
- dependsOn ":altJvmWarning"
- options.fork = true
- options.forkOptions.javaHome = jvmCurrent.javaHome
- }
+ // Any javac compilation tasks
+ tasks.withType(JavaCompile).configureEach {
+ dependsOn ":altJvmWarning"
+ options.fork = true
+ options.forkOptions.javaHome = jvmCurrent.javaHome
+ }
- // Javadoc compilation.
- def javadocExecutable = jvmCurrent.javadocExecutable
- tasks.matching { it.name == "renderJavadoc" || it.name == "renderSiteJavadoc" }.all {
- dependsOn ":altJvmWarning"
- executable = javadocExecutable.toString()
+ // Javadoc compilation.
+ def javadocExecutable = jvmCurrent.javadocExecutable
+ tasks.matching { it.name == "renderJavadoc" || it.name == "renderSiteJavadoc" }.configureEach {
+ dependsOn ":altJvmWarning"
+ executable = javadocExecutable.toString()
+ }
}
}
}
-// Set up root project's properties.
-rootProject.ext.runtimeJavaExecutable = jvmCurrent.javaExecutable
-rootProject.ext.runtimeJavaHome = jvmCurrent.javaHome
-rootProject.ext.runtimeJavaVersion = jvmDetector.getMetadata(InstallationLocation.userDefined(jvmCurrent.javaHome, "specific path")).getLanguageVersion()
-rootProject.ext.usesAltJvm = (jvmGradle != jvmCurrent);
-
+// Expose these properties on the root project. We could use an extension here, it'd be nicer.
+ext {
+ runtimeJavaExecutable = jvmCurrent.javaExecutable
+ runtimeJavaHome = jvmCurrent.javaHome
+ runtimeJavaVersion = jvmDetector.getMetadata(InstallationLocation.userDefined(jvmCurrent.javaHome, "specific path")).getLanguageVersion()
+ usesAltJvm = (jvmGradle != jvmCurrent);
+}
diff --git a/gradle/testing/beasting.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.beasting.gradle
similarity index 64%
rename from gradle/testing/beasting.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.beasting.gradle
index 67c20140ba8..b86917e5ad5 100644
--- a/gradle/testing/beasting.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.beasting.gradle
@@ -18,58 +18,62 @@
// This adds 'beast' task which clones tests a given number of times (preferably
// constrained with a filtering pattern passed via '--tests').
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
// TODO: subtasks are not run in parallel (sigh, gradle removed this capability for intra-project tasks).
// TODO: maybe it would be better to take a deeper approach and just feed the task
// runner duplicated suite names (much like https://github.com/gradle/test-retry-gradle-plugin)
// TODO: this is a somewhat related issue: https://github.com/gradle/test-retry-gradle-plugin/issues/29
-def beastingMode = gradle.startParameter.taskNames.any{ name -> name == 'beast' || name.endsWith(':beast') }
+def beastingMode = gradle.startParameter.taskNames.any { name -> name == 'beast' || name.endsWith(':beast') }
+def rootSeedUserProvided = rootProject.ext.rootSeedUserProvided
-allprojects {
- plugins.withType(JavaPlugin) {
- project.ext {
- testOptions += [
- [propName: 'tests.dups', value: 0, description: "Reiterate runs of entire test suites ('beast' task)."]
- ]
- }
+if (beastingMode) {
+ if (rootSeedUserProvided) {
+ rootProject.tasks.register("warnAboutConstantSeed", {
+ doFirst {
+ logger.warn("Root randomization seed is externally provided, all duplicated runs will use the same starting seed.")
+ }
+ })
}
}
-if (beastingMode) {
- if (rootProject.rootSeedUserProvided) {
- logger.warn("Root randomization seed is externally provided, all duplicated runs will use the same starting seed.")
- }
+allprojects {
+ plugins.withType(JavaPlugin).configureEach {
+ Provider<Integer> dupsOption = buildOptions.addIntOption("tests.dups", "Reiterate runs of entire test suites this many times ('beast' task).")
- allprojects {
- plugins.withType(JavaPlugin) {
- task beast(type: BeastTask) {
- description "Run a test suite (or a set of tests) many times over (duplicate 'test' task)."
- group "Verification"
- }
+ if (beastingMode) {
+ def beastTask = tasks.register("beast", BeastTask, {
+ description = "Run a test suite (or a set of tests) many times over (duplicate 'test' task)."
+ group = "Verification"
+ })
- def dups = Integer.parseInt(resolvedTestOption("tests.dups") as String)
- if (dups <= 0) {
+ if (!dupsOption.isPresent()) {
throw new GradleException("Specify -Ptests.dups=[count] for beast task.")
}
// generate N test tasks and attach them to the beasting task for this project;
// the test filter will be applied by the beast task once it is received from
// command line.
- def subtasks = (1..dups).collect { value ->
- return tasks.create(name: "test_${value}", type: Test, {
+ def subtasks = (1..dupsOption.get()).collect { value ->
+ return tasks.register("test_${value}", Test, {
failFast = true
doFirst {
// If there is a global root seed, use it (all duplicated tasks will run
// from the same starting seed). Otherwise pick a sequential derivative.
- if (!rootProject.rootSeedUserProvided) {
+ if (!rootSeedUserProvided) {
systemProperty("tests.seed",
- String.format("%08X", new Random(rootProject.rootSeedLong + value).nextLong()))
+ String.format("%08X", new Random(rootProject.ext.rootSeedLong + value).nextLong()))
}
}
})
}
- beast.dependsOn subtasks
+ beastTask.configure {
+ dependsOn subtasks
+ }
}
}
}
@@ -78,7 +82,7 @@ if (beastingMode) {
* We have to declare a dummy task here to be able to reuse the same syntax for 'test' task
* filter option.
*/
-class BeastTask extends DefaultTask {
+abstract class BeastTask extends DefaultTask {
@Option(option = "tests", description = "Sets test class or method name to be included, '*' is supported.")
public void setTestNamePatterns(List<String> patterns) {
taskDependencies.getDependencies(this).each { subtask ->
@@ -89,4 +93,4 @@ class BeastTask extends DefaultTask {
@TaskAction
void run() {
}
-}
\ No newline at end of file
+}
diff --git a/gradle/java/core-mrjar.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.core.mrjar.gradle
similarity index 80%
rename from gradle/java/core-mrjar.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.core.mrjar.gradle
index 8599fc39a10..60a4588ba2d 100644
--- a/gradle/java/core-mrjar.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.core.mrjar.gradle
@@ -18,27 +18,30 @@
// Produce an MR-JAR for panama vector implementations
configure(project(":lucene:core")) {
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
mrjarJavaVersions.each { jdkVersion ->
sourceSets.create("main${jdkVersion}") {
java {
srcDirs = ["src/java${jdkVersion}"]
}
}
- configurations["main${jdkVersion}Implementation"].extendsFrom(configurations['implementation'])
+
+ configurations["main${jdkVersion}Implementation"].extendsFrom(configurations.maybeCreate("implementation"))
dependencies.add("main${jdkVersion}Implementation", sourceSets.main.output)
tasks.named("compileMain${jdkVersion}Java").configure {
def apijar = apijars.file("jdk${jdkVersion}.apijar")
-
+
int releaseIndex = options.compilerArgs.indexOf("--release")
options.compilerArgs.removeAt(releaseIndex)
options.compilerArgs.removeAt(releaseIndex)
options.compilerArgs += [
"-Xlint:-options",
- "--add-exports", "java.base/java.lang.foreign=ALL-UNNAMED",
+ "--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",
+ "--add-exports",
+ "java.base/jdk.incubator.vector=ALL-UNNAMED",
]
def argsProvider = objects.newInstance(CompilerArgsProvider)
@@ -46,13 +49,15 @@ configure(project(":lucene:core")) {
options.compilerArgumentProviders.add(argsProvider)
}
}
-
+
tasks.named('jar').configure {
- boolean needMRJAR = false;
+ boolean needMRJAR = false
+ int minJavaVersion = Integer.parseInt(JavaVersion.toVersion(deps.versions.minJava.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 <= rootProject.minJavaVersion.toString() as int)
+ boolean isBaseVersion = (jdkVersion.toString() as int) <= minJavaVersion
into(isBaseVersion ? '' : "META-INF/versions/${jdkVersion}") {
from sourceSets["main${jdkVersion}"].output
}
@@ -61,8 +66,8 @@ configure(project(":lucene:core")) {
if (needMRJAR) {
manifest.attributes(
- 'Multi-Release': 'true'
- )
+ 'Multi-Release': 'true'
+ )
}
}
}
@@ -75,6 +80,9 @@ abstract class CompilerArgsProvider implements CommandLineArgumentProvider {
@Override
Iterable<String> asArguments() {
- return ["--patch-module", "java.base=${apiJarFile.get().asFile.absolutePath}".toString()]
+ return [
+ "--patch-module",
+ "java.base=${apiJarFile.get().asFile.absolutePath}".toString()
+ ]
}
}
diff --git a/gradle/testing/coverage.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.coverage.gradle
similarity index 54%
rename from gradle/testing/coverage.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.coverage.gradle
index 13c6de68d7f..228b04db861 100644
--- a/gradle/testing/coverage.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.coverage.gradle
@@ -17,41 +17,44 @@
// This adds jacoco code coverage to tests.
-// Run with jacoco if either 'coverage' is passed as a task on input or
-// tests.coverage property is true.
-def withCoverage = gradle.startParameter.taskNames.contains("coverage") ||
- Boolean.parseBoolean(propertyOrDefault("tests.coverage", "false"))
+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) {
- configure(rootProject) {
- plugins.apply("org.barfuin.gradle.jacocolog")
+ plugins.apply(deps.plugins.jacocolog.get().pluginId)
- // Synthetic task to enable test coverage (and aggregated reports).
- task coverage() {
- dependsOn jacocoAggregatedReport
- }
+ // Synthetic task to enable test coverage (and aggregated reports).
- configure(jacocoAggregatedReport) {
- doLast {
- logger.lifecycle("Code coverage report at: ${reports.html.entryPoint}\n")
- }
+ def jacocoAggregatedReport = tasks.named("jacocoAggregatedReport")
+ tasks.register("coverage", {
+ dependsOn jacocoAggregatedReport
+ })
+
+ jacocoAggregatedReport.configure {
+ doLast {
+ logger.lifecycle("Aggregated code coverage report at: ${reports.html.entryPoint}\n")
}
}
- allprojects {
- plugins.withType(JavaPlugin) {
- // Apply jacoco once we know the project has a Java plugin too.
- project.plugins.apply("org.barfuin.gradle.jacocolog")
+ subprojects {
+ plugins.apply(deps.plugins.jacocolog.get().pluginId)
+ plugins.withType(JavaPlugin).configureEach {
// Synthetic task to enable test coverage (and reports).
- task coverage() {
- dependsOn test, jacocoTestReport
- }
+ def jacocoTestReport = tasks.named("jacocoTestReport")
+ tasks.register("coverage", {
+ dependsOn "test", jacocoTestReport
+ })
- tasks.withType(Test) { Task testTask ->
+ tasks.withType(Test).configureEach { testTask ->
// Configure jacoco destination file to be within the test
- // task's working directory - this is related to security
- // manager permissions (access to this file from within test jvm).
+ // task's working directory
jacoco {
destinationFile = file("${testTask.workingDir}/jacoco.exec")
}
@@ -60,7 +63,7 @@ if (withCoverage) {
testTask.finalizedBy jacocoTestReport
}
- configure(jacocoTestReport) {
+ jacocoTestReport.configure {
doLast {
logger.lifecycle("Code coverage report at: ${reports.html.entryPoint}.\n")
}
diff --git a/gradle/testing/fail-on-no-tests.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.fail-on-no-tests.gradle
similarity index 56%
rename from gradle/testing/fail-on-no-tests.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.fail-on-no-tests.gradle
index db763d80277..4c3edaa7561 100644
--- a/gradle/testing/fail-on-no-tests.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.fail-on-no-tests.gradle
@@ -17,46 +17,44 @@
// 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) {
- tasks.withType(Test) {
+ plugins.withType(JavaPlugin).configureEach {
+ tasks.withType(Test).configureEach {
filter {
failOnNoMatchingTests = false
}
- }
- }
-}
-
-gradle.taskGraph.whenReady { graph ->
- def args = gradle.startParameter.taskNames
- def filters = args.findAll({ arg ->
- return arg == /--tests/
- })
- // Only apply the check if we are actually filtering.
- if (!filters.isEmpty()) {
- def testTasks = graph.allTasks.findAll { task -> task instanceof Test }
- // ... and there are some test tasks in the execution graph.
- if (!testTasks.isEmpty()) {
- def executedTests = 0
- def executedTasks = 0
-
- testTasks.each { task ->
- task.doFirst {
+ // Only apply the check if we are actually filtering.
+ if (doCount) {
+ doFirst {
executedTasks++
}
- task.afterSuite { desc, result ->
+ afterSuite { desc, result ->
executedTests += result.testCount
}
}
-
- // 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?")
- }
- }
}
}
}
+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/gradle/testing/per-project-summary.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.folder-layout.gradle
similarity index 57%
rename from gradle/testing/per-project-summary.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.folder-layout.gradle
index 14acfab8a85..81020aa6b1f 100644
--- a/gradle/testing/per-project-summary.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.folder-layout.gradle
@@ -15,23 +15,31 @@
* limitations under the License.
*/
+sourceSets {
+ main.java.srcDirs = ['src/java']
+ main.resources.srcDirs = ['src/resources']
+ test.java.srcDirs = ['src/test']
+ test.resources.srcDirs = ['src/test-files']
+}
-// Per-project test summary.
-
-allprojects {
- tasks.withType(Test) { task ->
- afterSuite { desc, result ->
- if (!desc.parent) {
- if (result.testCount > 0) {
- def components = [
- "test(s)" : result.testCount,
- "failure(s)": result.failedTestCount,
- "skipped" : result.skippedTestCount
- ].findAll { k, v -> v > 0 }.collect { k, v -> "$v $k" }.join(", ")
+tasks.named('processTestResources').configure {
+ from('src/test') {
+ exclude '**/*.java'
+ }
+}
- logger.lifecycle("${task.path} (${result.resultType}): ${components}")
- }
+// if 'src/tools' exists, add it as a separate sourceSet.
+if (project.file('src/tools/java').exists()) {
+ sourceSets {
+ tools {
+ java {
+ srcDirs = ['src/tools/java']
}
}
}
+
+ // Inherit any dependencies for this source set from the main source set.
+ configurations {
+ toolsImplementation.extendsFrom implementation
+ }
}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.jar-manifest.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.jar-manifest.gradle
new file mode 100644
index 00000000000..acc22e1f467
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.jar-manifest.gradle
@@ -0,0 +1,79 @@
+/*
+ * 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.environment.GitInfoExtension
+
+// Configures artifact JARs (manifest entries)
+
+def legaleseDir = rootProject.layout.projectDirectory.asFile
+
+Provider<String> gitRevProvider = rootProject.extensions.getByType(GitInfoExtension)
+ .gitInfo.getting("git.commit").orElse("-")
+
+// Declare these inline for now. Don't know if it makes sense to declare them
+// per-project.
+def title = "Lucene Search Engine: ${project.name}"
+def implementationTitle = "org.apache.lucene"
+
+// Apply the manifest to any JAR or WAR file created by any project.
+tasks.withType(Jar).configureEach { task ->
+ task.inputs.property("gitRev", gitRevProvider)
+
+ // Because git status is a task we must defer computing this
+ // until status has been computed. We do this with a provider.
+ def implementationVersion = provider {
+ // For snapshot builds just include the project version and gitRev so that
+ // JARs don't need to be recompiled just because the manifest has changed.
+ String gitRev = gitRevProvider.get()
+ if (rootProject.ext.snapshotBuild) {
+ return "${project.version} ${gitRev} [snapshot build, details omitted]"
+ } else {
+ return "${project.version} ${gitRev} - ${rootProject.ext.buildDate} ${rootProject.ext.buildTime}"
+ }
+ }
+
+ def manifestAttrs = [
+ "Extension-Name" : implementationTitle,
+
+ "Implementation-Vendor" : "The Apache Software Foundation",
+ "Implementation-Title" : implementationTitle,
+ "Implementation-Version": implementationVersion,
+
+ "Specification-Vendor" : "The Apache Software Foundation",
+ "Specification-Version" : project.baseVersion,
+ "Specification-Title" : title,
+
+ // Evaluate these properties lazily so that the defaults are applied properly.
+ "X-Compile-Source-JDK" : "${-> project.sourceCompatibility}",
+ "X-Compile-Target-JDK" : "${-> project.targetCompatibility}",
+
+ "X-Build-JDK" : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})",
+ "X-Build-OS" : "${System.properties['os.name']} ${System.properties['os.arch']} ${System.properties['os.version']}"
+ ]
+
+ manifest {
+ attributes(manifestAttrs)
+ }
+
+ // Copy legalese into META-INF.
+ metaInf {
+ from(legaleseDir, {
+ include "LICENSE.txt"
+ include "NOTICE.txt"
+ })
+ }
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.javac.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.javac.gradle
new file mode 100644
index 00000000000..8f20d9c030b
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.javac.gradle
@@ -0,0 +1,88 @@
+/*
+ * 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 minJavaVersion = JavaVersion.toVersion(deps.versions.minJava.get())
+
+Provider<Boolean> failOnWarningsOption = buildOptions.addBooleanOption("javac.failOnWarnings", "Triggers failures on javac warnings.", true)
+
+java {
+ sourceCompatibility = minJavaVersion
+ targetCompatibility = minJavaVersion
+}
+
+tasks.withType(JavaCompile).configureEach {
+ // Use 'release' flag instead of 'source' and 'target'
+ options.compilerArgs += [
+ "--release",
+ minJavaVersion.toString()
+ ]
+
+ // Configure warnings.
+ // Use 'javac --help-lint' to get the supported list
+ options.encoding = "UTF-8"
+ options.compilerArgs += [
+ "-Xlint:auxiliaryclass",
+ "-Xlint:cast",
+ "-Xlint:classfile",
+ "-Xlint:-deprecation",
+ "-Xlint:dep-ann",
+ "-Xlint:divzero",
+ "-Xlint:empty",
+ // TODO: uh-oh we have broken APIs.
+ "-Xlint:-exports",
+ "-Xlint:fallthrough",
+ "-Xlint:finally",
+ // TODO: untested
+ "-Xlint:-missing-explicit-ctor",
+ "-Xlint:module",
+ "-Xlint:opens",
+ "-Xlint:options",
+ "-Xlint:overloads",
+ "-Xlint:overrides",
+ // TODO: some tests seem to have bad classpaths?
+ // this check seems to be a good sanity check for gradle?
+ "-Xlint:-path",
+ "-Xlint:processing",
+ "-Xlint:rawtypes",
+ "-Xlint:removal",
+ "-Xlint:requires-automatic",
+ "-Xlint:requires-transitive-automatic",
+ "-Xlint:-serial",
+ "-Xlint:static",
+ "-Xlint:strictfp",
+ "-Xlint:synchronization",
+ "-Xlint:text-blocks",
+ "-Xlint:try",
+ "-Xlint:unchecked",
+ "-Xlint:varargs",
+ "-Xlint:preview",
+ "-Xdoclint:all/protected",
+ "-Xdoclint:-missing",
+ "-Xdoclint:-accessibility"
+ ]
+
+ if (project.path == ":lucene:benchmark-jmh") {
+ // JMH benchmarks use JMH preprocessor and incubating modules.
+ } else {
+ // proc:none was added because of LOG4J2-1925 / JDK-8186647
+ options.compilerArgs += ["-proc:none"]
+
+ if (failOnWarningsOption.get()) {
+ options.compilerArgs += "-Werror"
+ }
+ }
+}
diff --git a/gradle/java/modules.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.modules.gradle
similarity index 86%
rename from gradle/java/modules.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.modules.gradle
index cb8f7c8df34..591b7ffe0b6 100644
--- a/gradle/java/modules.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.modules.gradle
@@ -20,13 +20,10 @@ import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
-// Configure miscellaneous aspects required for supporting the java module system layer.
-
-// Debugging utilities.
-apply from: buildscript.sourceFile.toPath().resolveSibling("modules-debugging.gradle")
+// Configures miscellaneous aspects required to support the java module system layer.
allprojects {
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
// We won't be using gradle's built-in automatic module finder.
java {
modularity.inferModulePath.set(false)
@@ -35,7 +32,7 @@ allprojects {
//
// Configure modular extensions for each source set.
//
- project.sourceSets.all { SourceSet sourceSet ->
+ project.sourceSets.configureEach { SourceSet sourceSet ->
// Create and register a source set extension for manipulating classpath/ module-path
ModularPathsExtension modularPaths = new ModularPathsExtension(project, sourceSet)
sourceSet.extensions.add("modularPaths", modularPaths)
@@ -44,9 +41,9 @@ allprojects {
// support all of the module-specific javac options.
ModularPathsExtension modularPathsForEcj = modularPaths
if (sourceSet.name == SourceSet.TEST_SOURCE_SET_NAME && project.path in [
- ":lucene:spatial-extras",
- ":lucene:spatial3d",
- ]) {
+ ":lucene:spatial-extras",
+ ":lucene:spatial3d",
+ ]) {
modularPathsForEcj = modularPaths.cloneWithMode(ModularPathsExtension.Mode.CLASSPATH_ONLY)
}
sourceSet.extensions.add("modularPathsForEcj", modularPathsForEcj)
@@ -54,12 +51,12 @@ allprojects {
// TODO: the tests of these projects currently don't compile or work in
// module-path mode. Make the modular paths extension use class path only.
if (sourceSet.name == SourceSet.TEST_SOURCE_SET_NAME && project.path in [
- // Circular dependency between artifacts or source set outputs,
- // causing package split issues at runtime.
- ":lucene:core",
- ":lucene:codecs",
- ":lucene:test-framework",
- ]) {
+ // Circular dependency between artifacts or source set outputs,
+ // causing package split issues at runtime.
+ ":lucene:core",
+ ":lucene:codecs",
+ ":lucene:test-framework",
+ ]) {
modularPaths.mode = ModularPathsExtension.Mode.CLASSPATH_ONLY
}
@@ -141,12 +138,12 @@ allprojects {
testSourceSet.compileClasspath = project.objects.fileCollection().from(
jarTaskOutputs,
project.configurations.getByName(testSourceSet.getCompileClasspathConfigurationName()),
- )
+ )
testSourceSet.runtimeClasspath = project.objects.fileCollection().from(
jarTaskOutputs,
testJarTask.outputs,
project.configurations.getByName(testSourceSet.getRuntimeClasspathConfigurationName()),
- )
+ )
project.dependencies {
moduleTestImplementation files(jarTaskOutputs)
@@ -200,11 +197,13 @@ allprojects {
// Pass all the required properties for tests which fork the JVM. We don't use
// regular system properties here because this could affect task up-to-date checks.
jvmArgumentProviders.add(new CommandLineArgumentProvider() {
- @Override
- Iterable<String> asArguments() {
- return ["-Dtests.jvmForkArgsFile=" + forkProperties.absolutePath]
- }
- })
+ @Override
+ Iterable<String> asArguments() {
+ return [
+ "-Dtests.jvmForkArgsFile=" + forkProperties.absolutePath
+ ]
+ }
+ })
doFirst {
List<String> args = new ArrayList<>(modularPaths.runtimeArguments.asArguments().collect())
def cp = modularPaths.runtimeClasspath.asPath
@@ -213,7 +212,7 @@ allprojects {
}
// Sanity check.
- args.forEach(s -> {
+ args.forEach({s ->
if (s.contains("\n")) {
throw new RuntimeException("LF in forked jvm property?: " + s)
}
@@ -226,16 +225,20 @@ allprojects {
}
// Configure (tasks.test, sourceSets.test)
- tasks.matching { it.name ==~ /test(_[0-9]+)?/ }.all { Test task ->
+ tasks.matching { it.name ==~ /test(_[0-9]+)?/ }.configureEach { Test task ->
configureTestTaskForSourceSet(task, task.project.sourceSets.test)
}
// Configure module versions.
tasks.withType(JavaCompile).configureEach { task ->
// TODO: LUCENE-10267: workaround for gradle bug. Remove when the corresponding issue is fixed.
- task.options.compilerArgumentProviders.add((CommandLineArgumentProvider) { ->
+ task.options.compilerArgumentProviders.add((CommandLineArgumentProvider) {
+ ->
if (task.getClasspath().isEmpty()) {
- return ["--module-version", project.version.toString()]
+ return [
+ "--module-version",
+ project.version.toString()
+ ]
} else {
return []
}
@@ -312,7 +315,8 @@ class ModularPathsExtension implements Cloneable, Iterable<Object> {
this.project = project
this.sourceSet = sourceSet
- debugPaths = Boolean.parseBoolean(project.propertyOrDefault('build.debug.paths', 'false'))
+ // enable to debug paths.
+ debugPaths = false
ConfigurationContainer configurations = project.configurations
@@ -388,7 +392,7 @@ class ModularPathsExtension implements Cloneable, Iterable<Object> {
if (hasModuleDescriptor()) {
// The source set is itself a module.
throw new GradleException("Source set contains a module but classpath-only" +
- " dependencies requested: ${project.path}, source set '${sourceSet.name}'")
+ " dependencies requested: ${project.path}, source set '${sourceSet.name}'")
}
return project.files()
@@ -404,38 +408,45 @@ class ModularPathsExtension implements Cloneable, Iterable<Object> {
// Modify the default classpath by removing anything already placed on module path.
// Use a lazy provider to delay computation.
- project.files({ ->
+ project.files({
+ ->
return sourceSet.compileClasspath - compileModulePathConfiguration - modulePatchOnlyConfiguration
})
}
CommandLineArgumentProvider getCompilationArguments() {
return new CommandLineArgumentProvider() {
- @Override
- Iterable<String> asArguments() {
- FileCollection modulePath = ModularPathsExtension.this.compilationModulePath
-
- if (modulePath.isEmpty()) {
- return []
- }
+ @Override
+ Iterable<String> asArguments() {
+ FileCollection modulePath = ModularPathsExtension.this.compilationModulePath
- ArrayList<String> extraArgs = []
- extraArgs += ["--module-path", modulePath.join(File.pathSeparator)]
+ if (modulePath.isEmpty()) {
+ return []
+ }
- if (!hasModuleDescriptor()) {
- // We're compiling what appears to be a non-module source set so we'll
- // bring everything on module path in the resolution graph,
- // otherwise modular dependencies wouldn't be part of the resolved module graph and this
- // would result in class-not-found compilation problems.
- extraArgs += ["--add-modules", "ALL-MODULE-PATH"]
- }
+ ArrayList<String> extraArgs = []
+ extraArgs += [
+ "--module-path",
+ modulePath.join(File.pathSeparator)
+ ]
+
+ if (!hasModuleDescriptor()) {
+ // We're compiling what appears to be a non-module source set so we'll
+ // bring everything on module path in the resolution graph,
+ // otherwise modular dependencies wouldn't be part of the resolved module graph and this
+ // would result in class-not-found compilation problems.
+ extraArgs += [
+ "--add-modules",
+ "ALL-MODULE-PATH"
+ ]
+ }
- // Add module-patching.
- extraArgs += getPatchModuleArguments(modulePatches)
+ // Add module-patching.
+ extraArgs += getPatchModuleArguments(modulePatches)
- return extraArgs
- }
- }
+ return extraArgs
+ }
+ }
}
FileCollection getRuntimeClasspath() {
@@ -445,43 +456,50 @@ class ModularPathsExtension implements Cloneable, Iterable<Object> {
// Modify the default classpath by removing anything already placed on module path.
// Use a lazy provider to delay computation.
- project.files({ ->
+ project.files({
+ ->
return sourceSet.runtimeClasspath - runtimeModulePath - modulePatchOnlyConfiguration
})
}
CommandLineArgumentProvider getRuntimeArguments() {
return new CommandLineArgumentProvider() {
- @Override
- Iterable<String> asArguments() {
- FileCollection modulePath = ModularPathsExtension.this.runtimeModulePath
+ @Override
+ Iterable<String> asArguments() {
+ FileCollection modulePath = ModularPathsExtension.this.runtimeModulePath
- if (modulePath.isEmpty()) {
- return []
- }
+ if (modulePath.isEmpty()) {
+ return []
+ }
- def extraArgs = []
+ def extraArgs = []
- // Add source set outputs to module path.
- extraArgs += ["--module-path", modulePath.files.join(File.pathSeparator)]
+ // Add source set outputs to module path.
+ extraArgs += [
+ "--module-path",
+ modulePath.files.join(File.pathSeparator)
+ ]
- // Ideally, we should only add the sourceset's module here, everything else would be resolved via the
- // module descriptor. But this would require parsing the module descriptor and may cause JVM version conflicts
- // so keeping it simple.
- extraArgs += ["--add-modules", "ALL-MODULE-PATH"]
+ // Ideally, we should only add the sourceset's module here, everything else would be resolved via the
+ // module descriptor. But this would require parsing the module descriptor and may cause JVM version conflicts
+ // so keeping it simple.
+ extraArgs += [
+ "--add-modules",
+ "ALL-MODULE-PATH"
+ ]
- // Add module-patching.
- extraArgs += getPatchModuleArguments(modulePatches)
+ // Add module-patching.
+ extraArgs += getPatchModuleArguments(modulePatches)
- return extraArgs
- }
- }
+ return extraArgs
+ }
+ }
}
boolean hasModuleDescriptor() {
return sourceSet.allJava.srcDirs.stream()
- .map(dir -> new File(dir, "module-info.java"))
- .anyMatch(file -> file.exists())
+ .map {dir -> new File(dir, "module-info.java") }
+ .anyMatch {file -> file.exists() }
}
private List<String> getPatchModuleArguments(List<Map.Entry<String, Provider<Path>>> patches) {
@@ -561,8 +579,8 @@ class ModularPathsExtension implements Cloneable, Iterable<Object> {
@Override
Iterator<Object> iterator() {
return [
- compileModulePathConfiguration,
- runtimeModulePathConfiguration
+ compileModulePathConfiguration,
+ runtimeModulePathConfiguration
].iterator()
}
-}
\ No newline at end of file
+}
diff --git a/gradle/conventions.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.per-project-test-summary.gradle
similarity index 62%
rename from gradle/conventions.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.per-project-test-summary.gradle
index eb676dcb189..c52b20813ad 100644
--- a/gradle/conventions.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.per-project-test-summary.gradle
@@ -15,19 +15,20 @@
* limitations under the License.
*/
-configure(allprojects) {
- tasks.register("tidy").configure {
- description "Applies formatters and cleanups to sources."
- group "verification"
- }
-}
+// Prints per-project test summary.
-// Locate script-relative resource folder. This is context-sensitive so pass
-// the right buildscript (top-level).
-configure(rootProject) {
- ext {
- scriptResources = { buildscript ->
- return file(buildscript.sourceFile.absolutePath.replaceAll('.gradle$', ""))
+tasks.withType(Test).configureEach { task ->
+ afterSuite { desc, result ->
+ if (!desc.parent) {
+ if (result.testCount > 0) {
+ def components = [
+ "test(s)" : result.testCount,
+ "failure(s)": result.failedTestCount,
+ "skipped" : result.skippedTestCount
+ ].findAll { k, v -> v > 0 }.collect { k, v -> "$v $k" }.join(", ")
+
+ logger.lifecycle("${task.path} (${result.resultType}): ${components}")
+ }
}
}
-}
\ No newline at end of file
+}
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
new file mode 100644
index 00000000000..029dfbb1e4b
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.profiling.gradle
@@ -0,0 +1,72 @@
+/*
+ * 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/groovy/lucene.java.show-failed-tests-at-end.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.show-failed-tests-at-end.gradle
new file mode 100644
index 00000000000..5c76ca592ac
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.show-failed-tests-at-end.gradle
@@ -0,0 +1,72 @@
+/*
+ * 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.ErrorReportingTestListener
+
+// Display all failed tests at the end of the build.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+def failedTests = []
+
+allprojects {
+ plugins.withType(JavaPlugin).configureEach {
+ tasks.withType(Test).configureEach { Test task ->
+ def testOutputsDir = task.ext.testOutputsDir
+ def reproLine = ErrorReportingTestListener.getReproLineOptions(task)
+
+ afterTest { desc, result ->
+ if (result.resultType == TestResult.ResultType.FAILURE) {
+ failedTests << [
+ "name" : "${desc.className}.${desc.name}",
+ "project" : "${test.project.path}",
+ "output" : file("${testOutputsDir}/${ErrorReportingTestListener.getOutputLogName(desc.parent)}"),
+ "reproduce": "gradlew ${project.path}:test --tests \"${desc.className}.${desc.name}\" ${reproLine}"
+ ]
+ }
+ }
+
+ afterSuite { desc, result ->
+ if (result.exceptions) {
+ failedTests << [
+ "name" : "${desc.name}",
+ "project" : "${test.project.path}",
+ "output" : file("${testOutputsDir}/${ErrorReportingTestListener.getOutputLogName(desc)}"),
+ "reproduce": "gradlew ${project.path}:test --tests \"${desc.name}\" ${reproLine}"
+ ]
+ }
+ }
+ }
+ }
+}
+
+gradle.buildFinished { result ->
+ if (failedTests) {
+ def formatted = failedTests
+ .sort { a, b -> b.project.compareTo(a.project) }
+ .collect { e ->
+ String.format(Locale.ROOT,
+ " - %s (%s)\n Test output: %s\n Reproduce with: %s\n",
+ e.name, e.project, e.output, e.reproduce)
+ }
+ .join("\n")
+
+ logger.error("\nERROR: The following test(s) have failed:\n${formatted}")
+ }
+}
diff --git a/gradle/testing/slowest-tests-at-end.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.slowest-tests-at-end.gradle
similarity index 63%
rename from gradle/testing/slowest-tests-at-end.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.java.slowest-tests-at-end.gradle
index d24e523394d..a6f1750a425 100644
--- a/gradle/testing/slowest-tests-at-end.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.slowest-tests-at-end.gradle
@@ -17,40 +17,44 @@
// Add test duration summary at the end of the build.
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
def allTests = []
def allSuites = []
allprojects {
- plugins.withType(JavaPlugin) {
- project.ext {
- testOptions += [
- [propName: 'tests.slowestTests', value: true, description: "Print the summary of the slowest tests."],
- [propName: 'tests.slowestSuites', value: true, description: "Print the summary of the slowest suites."]
- ]
- }
+ plugins.withType(JavaPlugin).configureEach {
+ Provider<Boolean> slowestTestsOption = buildOptions.addBooleanOption("tests.slowestTests", "Print the summary of the slowest tests.", true)
+ int slowestTestsMinTime = buildOptions.addIntOption("tests.slowestTests.minTime", "Minimum test time to consider a test slow (millis).", 500).get()
+ Provider<Boolean> slowestSuitesOption = buildOptions.addBooleanOption("tests.slowestSuites", "Print the summary of the slowest suites.", true)
+ int slowestSuitesMinTime = buildOptions.addIntOption("tests.slowestSuites.minTime", "Minimum suite time to consider a suite slow (millis).", 1000).get()
- tasks.withType(Test) { task ->
- if (resolvedTestOption("tests.slowestTests").toBoolean()) {
+ tasks.withType(Test).configureEach { task ->
+ if (slowestTestsOption.get()) {
afterTest { desc, result ->
def duration = (result.getEndTime() - result.getStartTime())
-
- allTests << [
+ if (duration >= slowestTestsMinTime) {
+ allTests << [
name : "${desc.className.replaceAll('.+\\.', "")}.${desc.name} (${project.path})",
duration: duration
- ]
+ ]
+ }
}
}
- if (resolvedTestOption("tests.slowestSuites").toBoolean()) {
+ if (slowestSuitesOption.get()) {
afterSuite { desc, result ->
// Gradle reports runner times as well, omit anything that isn't attached to a concrete class.
if (desc.className != null) {
def duration = (result.getEndTime() - result.getStartTime())
-
- allSuites << [
+ if (duration >= slowestSuitesMinTime) {
+ allSuites << [
name : "${desc.className.replaceAll('.+\\.', "")} (${project.path})",
duration: duration
- ]
+ ]
+ }
}
}
}
@@ -64,12 +68,10 @@ gradle.buildFinished { result ->
def slowest = allTests
.sort { a, b -> b.duration.compareTo(a.duration) }
.take(10)
- .findAll { e -> e.duration >= 500 }
.collect { e -> String.format(Locale.ROOT, "%5.2fs %s", e.duration / 1000d, e.name) }
if (slowest) {
- logger.lifecycle("The slowest tests (exceeding 500 ms) during this run:\n " +
- slowest.join("\n "))
+ logger.lifecycle("The slowest tests during this run:\n " + slowest.join("\n "))
}
}
@@ -77,12 +79,10 @@ gradle.buildFinished { result ->
def slowest = allSuites
.sort { a, b -> b.duration.compareTo(a.duration) }
.take(10)
- .findAll { e -> e.duration >= 1000 }
.collect { e -> String.format(Locale.ROOT, "%5.2fs %s", e.duration / 1000d, e.name) }
if (slowest) {
- logger.lifecycle("The slowest suites (exceeding 1s) during this run:\n " +
- slowest.join("\n "))
+ logger.lifecycle("The slowest suites during this run:\n " + slowest.join("\n "))
}
}
}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.tests-and-randomization.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.tests-and-randomization.gradle
new file mode 100644
index 00000000000..909a7262cd4
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.java.tests-and-randomization.gradle
@@ -0,0 +1,342 @@
+/*
+ * 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.taskdefs.condition.Os
+import org.apache.tools.ant.types.Commandline
+import org.gradle.api.tasks.testing.logging.*
+import com.carrotsearch.randomizedtesting.generators.RandomPicks
+import org.apache.lucene.gradle.ErrorReportingTestListener
+
+def loggingConfigFile = rootProject.layout.projectDirectory.file("gradle/testing/logging.properties")
+def verboseModeHookInstalled = false
+
+// Pass certain build options to the test JVM as system properties
+def optionsInheritedAsProperties = []
+
+// JVM options
+Provider<String> minHeapSizeOption = buildOptions.addOption("tests.minheapsize", "Minimum heap size for test JVMs", "256m")
+Provider<String> heapSizeOption = buildOptions.addOption("tests.heapsize", "Heap size for test JVMs", "512m")
+
+// Vectorization related options.
+String randomVectorSize = RandomPicks.randomFrom(new Random(project.ext.projectSeedLong), [
+ "default",
+ "128",
+ "256",
+ "512"
+])
+Provider<Boolean> defaultvectorizationOption = buildOptions.addBooleanOption("tests.defaultvectorization",
+ "Uses defaults for running tests with correct JVM settings to test Panama vectorization (tests.jvmargs, tests.vectorsize, tests.forceintegervectors).", false)
+buildOptions.addOption("tests.vectorsize", "Sets preferred vector size in bits.", provider {
+ defaultvectorizationOption.get() ? 'default' : randomVectorSize
+})
+buildOptions.addBooleanOption("tests.forceintegervectors", "Forces use of integer vectors even when slow.", provider {
+ defaultvectorizationOption.get() ? false : (randomVectorSize != 'default')
+})
+optionsInheritedAsProperties += [
+ "tests.vectorsize",
+ "tests.forceintegervectors"
+]
+
+// Verbatim JVM arguments; make it also accept TEST_JVM_ARGS env. variable.
+Provider<String> jvmArgsOption = buildOptions.addOption("tests.jvmargs", "Arguments passed to each forked test JVM.",
+ provider {
+ ->
+ return (isCIBuild || defaultvectorizationOption.get()) ? "" : "-XX:TieredStopAtLevel=1 -XX:+UseParallelGC -XX:ActiveProcessorCount=1"
+ })
+jvmArgsOption = project.providers.environmentVariable("TEST_JVM_ARGS").orElse(jvmArgsOption)
+
+// cwd and tmp dir for forked JVMs.
+Provider<Directory> workDirOption = buildOptions.addDirOption("tests.workDir", "Working directory for forked test JVMs.",
+ project.layout.buildDirectory.dir("tests-cwd"))
+Provider<Directory> tmpDirOption = buildOptions.addDirOption("tests.tmpDir", "Temp directory for forked test JVMs.",
+ project.layout.buildDirectory.dir("tests-tmp"))
+def testsCwd = workDirOption.get().asFile
+def testsTmpDir = workDirOption.get().asFile
+
+// Asserts, debug output.
+Provider<Boolean> verboseOption = buildOptions.addBooleanOption("tests.verbose", "Enables verbose test output mode (emits full test outputs immediately).", false)
+Provider<Boolean> haltOnFailureOption = buildOptions.addBooleanOption("tests.haltonfailure", "Halt processing early on test failure.", false)
+Provider<Boolean> failFastOption = buildOptions.addBooleanOption("tests.failfast", "Stop the build early on failure.", false)
+Provider<Boolean> rerunOption = buildOptions.addBooleanOption("tests.rerun", "Always rerun the test task, even if nothing has changed on input.", true)
+
+// How many testing JVM forks to create
+Provider<Integer> jvmsOption = buildOptions.addIntOption("tests.jvms", "The number of forked test JVMs",
+ provider { -> ((int) Math.max(1, Math.min(Runtime.runtime.availableProcessors() / 2.0, 4.0))) })
+
+// GITHUB#13986: Allow easier configuration of the Panama Vectorization provider with newer Java versions
+Provider<Integer> upperJavaFeatureVersionOption = buildOptions.addIntOption(
+ "tests.upperJavaFeatureVersion", "Min JDK feature version to configure the Panama Vectorization provider")
+
+// Test reiteration, filtering and component randomization options.
+buildOptions.addIntOption("tests.iters", "Duplicate (re-run) each test case N times.")
+optionsInheritedAsProperties += ["tests.iters"]
+
+buildOptions.addIntOption("tests.multiplier", "Value multiplier for randomized tests.")
+optionsInheritedAsProperties += ["tests.multiplier"]
+
+buildOptions.addIntOption("tests.maxfailures", "Skip tests after a given number of failures.")
+optionsInheritedAsProperties += ["tests.maxfailures"]
+
+buildOptions.addIntOption("tests.timeoutSuite", "Timeout (in millis) for an entire suite.")
+optionsInheritedAsProperties += ["tests.timeoutSuite"]
+
+Provider<Boolean> assertsOption = buildOptions.addBooleanOption("tests.asserts", "Enables or disables assertions mode.", true)
+optionsInheritedAsProperties += ["tests.asserts"]
+
+buildOptions.addBooleanOption("tests.infostream", "Enables or disables infostream logs.", false)
+optionsInheritedAsProperties += ["tests.infostream"]
+
+buildOptions.addBooleanOption("tests.leaveTemporary", "Leave temporary directories after tests complete.", false)
+optionsInheritedAsProperties += ["tests.leaveTemporary"]
+
+buildOptions.addOption("tests.codec", "Sets the codec tests should run with.", "random")
+optionsInheritedAsProperties += ["tests.codec"]
+
+buildOptions.addOption("tests.directory", "Sets the Directory implementation tests should run with.", "random")
+optionsInheritedAsProperties += ["tests.directory"]
+
+buildOptions.addOption("tests.postingsformat", "Sets the postings format tests should run with.", "random")
+optionsInheritedAsProperties += ["tests.postingsformat"]
+
+buildOptions.addOption("tests.docvaluesformat", "Sets the doc values format tests should run with.", "random")
+optionsInheritedAsProperties += ["tests.docvaluesformat"]
+
+buildOptions.addOption("tests.locale", "Sets the default locale tests should run with.", "random")
+optionsInheritedAsProperties += ["tests.locale"]
+
+buildOptions.addOption("tests.timezone", "Sets the default time zone tests should run with.", "random")
+optionsInheritedAsProperties += ["tests.timezone"]
+
+buildOptions.addOption("tests.filter", "Applies a test filter (see ./gradlew :helpTests).")
+optionsInheritedAsProperties += ["tests.filter"]
+
+buildOptions.addBooleanOption("tests.nightly", "Enables or disables @Nightly tests.", false)
+buildOptions.addBooleanOption("tests.monster", "Enables or disables @Monster tests.", false)
+buildOptions.addBooleanOption("tests.awaitsfix", "Enables or disables @AwaitsFix tests.", false)
+optionsInheritedAsProperties += [
+ "tests.nightly",
+ "tests.monster",
+ "tests.awaitsfix"
+]
+
+buildOptions.addBooleanOption("tests.gui", "Enables or disables @RequiresGUI tests.", provider {
+ ->
+ return rootProject.ext.isCIBuild
+})
+
+buildOptions.addOption("tests.file.encoding", "Sets the default file.encoding on test JVM.", provider {
+ ->
+ return RandomPicks.randomFrom(new Random(project.ext.projectSeedLong), [
+ "US-ASCII",
+ "ISO-8859-1",
+ "UTF-8"
+ ])
+})
+
+// TODO: do we still use these?
+// Test data file used.
+// [propName: 'tests.linedocsfile', value: 'europarl.lines.txt.gz', description: "Test data file path."],
+// miscellaneous; some of them very weird.
+// [propName: 'tests.LUCENE_VERSION', value: baseVersion, description: "Base Lucene version."],
+// [propName: 'tests.bwcdir', value: null, description: "Data for backward-compatibility indexes."]
+
+
+// If we're running in verbose mode and:
+// 1) worker count > 1
+// 2) number of 'test' tasks in the build is > 1
+// then the output would very likely be mangled on the
+// console. Fail and let the user know what to do.
+def verboseMode = verboseOption.get().booleanValue()
+if (verboseMode && !verboseModeHookInstalled) {
+ verboseModeHookInstalled = true
+ if (gradle.startParameter.maxWorkerCount > 1) {
+ gradle.taskGraph.whenReady { graph ->
+ def testTasks = graph.allTasks.findAll { task -> task instanceof Test }
+ if (testTasks.size() > 1) {
+ throw new GradleException("Run your tests in verbose mode only with --max-workers=1 option passed to gradle.")
+ }
+ }
+ }
+}
+
+tasks.withType(Test).configureEach {
+ // Running any test task should first display the root randomization seed.
+ dependsOn ":showTestsSeed"
+
+ ext {
+ testOutputsDir = file("${reports.junitXml.outputLocation.get()}/outputs")
+ }
+
+ // LUCENE-9660: Make it possible to always rerun tests, even if they're incrementally up-to-date.
+ if (rerunOption.get()) {
+ outputs.upToDateWhen { false }
+ }
+
+ maxParallelForks = jvmsOption.get()
+ if (verboseMode && maxParallelForks != 1) {
+ logger.lifecycle("tests.jvm forced to 1 in verbose mode.")
+ maxParallelForks = 1
+ }
+
+ if (failFastOption.get()) {
+ failFast true
+ }
+
+ workingDir testsCwd
+ useJUnit()
+
+ minHeapSize = minHeapSizeOption.get()
+ maxHeapSize = heapSizeOption.get()
+
+ ignoreFailures = (haltOnFailureOption.get() == false)
+
+ // Up to JDK-15 we have to enforce --illegal-access=deny, because we want no code to access
+ // JDK internals; JDK-16 and later will default to deny, see https://openjdk.java.net/jeps/396:
+ if (rootProject.ext.runtimeJavaVersion < JavaVersion.VERSION_16) {
+ jvmArgs '--illegal-access=deny'
+ }
+
+ if (assertsOption.get()) {
+ jvmArgs("-ea", "-esa")
+ } else {
+ enableAssertions = false
+ }
+
+ // Lucene needs to optional modules at runtime, which we want to enforce for testing
+ // (if the runner JVM does not support them, it will fail tests):
+ jvmArgs '--add-modules', 'jdk.management'
+
+ // dump heap on OOM.
+ jvmArgs "-XX:+HeapDumpOnOutOfMemoryError"
+
+ // Enable the vector incubator module on supported Java versions:
+
+ Provider<Integer> minMajorVersion = upperJavaFeatureVersionOption.map { ver -> Integer.parseInt(JavaVersion.toVersion(ver).majorVersion) }
+ JavaVersion runtimeJava = rootProject.ext.runtimeJavaVersion
+ boolean incubatorJavaVersion = rootProject.ext.vectorIncubatorJavaVersions.contains(runtimeJava)
+ boolean manualMinMajorVersion = minMajorVersion.isPresent() &&
+ Integer.parseInt(runtimeJava.majorVersion) <= minMajorVersion.get()
+ if (incubatorJavaVersion || manualMinMajorVersion) {
+ jvmArgs '--add-modules', 'jdk.incubator.vector'
+ if (manualMinMajorVersion) {
+ systemProperty 'org.apache.lucene.vectorization.upperJavaFeatureVersion', Integer.toString(minMajorVersion.get())
+ }
+ }
+
+ jvmArgs '--enable-native-access=' + (project.path in [
+ ':lucene:core',
+ ':lucene:codecs',
+ ":lucene:distribution.tests",
+ ":lucene:test-framework"
+ ] ? 'ALL-UNNAMED' : 'org.apache.lucene.core')
+
+ def loggingFileProvider = new LoggingFileArgumentProvider()
+ loggingFileProvider.setLoggingConfigFile(loggingConfigFile)
+ loggingFileProvider.setTempDir(tmpDirOption.get())
+ jvmArgumentProviders.add(loggingFileProvider)
+
+ systemProperty 'java.awt.headless', 'true'
+ systemProperty 'jdk.map.althashing.threshold', '0'
+
+ if (!Os.isFamily(Os.FAMILY_WINDOWS)) {
+ systemProperty 'java.security.egd', 'file:/dev/./urandom'
+ }
+
+ // Pass certain buildOptions as system properties
+ for (String key : optionsInheritedAsProperties) {
+ def option = buildOptions.optionValue(key)
+ if (option.isPresent()) {
+ systemProperty(key, buildOptions.optionValue(key).get())
+ }
+ }
+
+ // Turn jenkins blood red for hashmap bugs
+ systemProperty 'jdk.map.althashing.threshold', '0'
+
+ // Set up cwd and temp locations.
+ systemProperty("java.io.tmpdir", testsTmpDir)
+ doFirst {
+ testsCwd.mkdirs()
+ testsTmpDir.mkdirs()
+ }
+
+ jvmArgs Commandline.translateCommandline(jvmArgsOption.get())
+
+ // Disable HTML report generation. The reports are big and slow to generate.
+ reports.html.required = false
+
+ // Set up logging.
+ testLogging {
+ events TestLogEvent.FAILED
+ exceptionFormat TestExceptionFormat.FULL
+ showExceptions true
+ showCauses true
+ showStackTraces true
+ stackTraceFilters.clear()
+ showStandardStreams false
+ }
+
+ // Disable automatic test class detection, rely on class names only. This is needed for testing
+ // against JDKs where the bytecode is unparseable by Gradle, for example.
+ // We require all tests to start with Test*, this simplifies include patterns greatly.
+ scanForTestClasses = false
+ include '**/Test*.class'
+ exclude '**/*$*'
+
+ // Set up custom test output handler.
+ doFirst {
+ project.delete testOutputsDir
+ }
+
+ def spillDir = getTemporaryDir().toPath()
+ def listener = new ErrorReportingTestListener(test.testLogging, spillDir, testOutputsDir.toPath(), verboseMode)
+ addTestOutputListener(listener)
+ addTestListener(listener)
+
+ doFirst {
+ // Print some diagnostics about locations used.
+ logger.info("Test folders for {}: cwd={}, tmp={}", project.path, testsCwd, testsTmpDir)
+ }
+}
+
+
+class LoggingFileArgumentProvider implements CommandLineArgumentProvider {
+ @InputFile
+ @PathSensitive(PathSensitivity.RELATIVE)
+ RegularFile loggingConfigFile
+
+ @Internal
+ Directory tempDir
+
+ @Override
+ Iterable<String> asArguments() {
+ [
+ "-Djava.util.logging.config.file=${loggingConfigFile.getAsFile()}",
+ "-DtempDir=${tempDir.getAsFile()}"
+ ]
+ }
+}
+
+
+ext {
+ // Resolves test option's value.
+ resolvedTestOption = { propName ->
+ return buildOptions[propName].get()
+ }
+
+ commonDir = project(":lucene").projectDir
+}
diff --git a/gradle/validation/measure-task-times.gradle b/build-tools/build-infra/src/main/groovy/lucene.misc.measure-task-times.gradle
similarity index 50%
rename from gradle/validation/measure-task-times.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.misc.measure-task-times.gradle
index c495d8d560d..b967d239ef9 100644
--- a/gradle/validation/measure-task-times.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.misc.measure-task-times.gradle
@@ -15,55 +15,64 @@
* limitations under the License.
*/
import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.TimeUnit
import java.util.stream.Collectors
// Measure aggregate wall time of each task execution time (summed up across
// all projects).
-if (propertyOrDefault("task.times", null) != null) {
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+Provider<Boolean> taskTimesOption = buildOptions.addBooleanOption("task.times",
+ "Measures wall-time task execution and provides a summary of the longest tasks at " +
+ "the end of a successful build.",
+ false)
+
+if (taskTimesOption.get()) {
gradle.taskGraph.whenReady { TaskExecutionGraph graph ->
def taskTimes = new ConcurrentHashMap<String, Long>()
- def measured = graph.allTasks.findAll { task -> true }
graph.addTaskExecutionListener(new TaskExecutionListener() {
- @Override
- void beforeExecute(Task task) {
- def start = System.currentTimeMillis()
- if (measured.contains(task)) {
- taskTimes.put(task.path, start)
- }
- }
+ @Override
+ void beforeExecute(Task task) {
+ def start = System.nanoTime()
+ taskTimes.put(task.path, start)
+ }
- @Override
- void afterExecute(Task task, TaskState taskState) {
- def stop = System.currentTimeMillis()
- if (measured.contains(task)) {
- if (taskState.didWork) {
- taskTimes.compute(task.path, { k, v -> stop - v })
- } else {
- taskTimes.remove(task.path)
+ @Override
+ void afterExecute(Task task, TaskState taskState) {
+ if (taskState.didWork) {
+ def stop = System.nanoTime()
+ taskTimes.compute(task.path, { k, v -> TimeUnit.NANOSECONDS.toMillis(stop - v) })
+ } else {
+ taskTimes.remove(task.path)
+ }
}
- }
- }
- })
+ })
// After the build is finished, check the test count.
gradle.buildFinished {
// Compute aggregate times of all task execution times.
def aggregates = taskTimes.entrySet().stream()
.collect(Collectors.groupingBy({e -> e.key.replaceAll(".*:", "")}))
- .entrySet().stream()
- .collect(Collectors.toMap(
- {e -> e.key },
- {e -> e.value.stream().mapToLong({ entry -> entry.value }).sum() }
- ))
+ .entrySet().stream()
+ .collect(Collectors.toMap(
+ {e -> e.key }, {e ->
+ e.value.stream().mapToLong({ entry -> entry.value }).sum()
+ }
+ ))
- logger.lifecycle("Aggregate task times (possibly running in parallel!):")
- aggregates.entrySet().stream()
- .sorted({a, b -> Long.compare(b.value, a.value) })
- .forEach {v ->
- logger.lifecycle(String.format(Locale.ROOT, " %6.2f sec. %s", v.value / 1000.0, v.key))
- }
+ logger.lifecycle("\nAggregate task times (possibly running in parallel!):\n"
+ + aggregates
+ .sort {a, b ->
+ Long.compare(b.value, a.value)
+ }
+ .collect { v ->
+ String.format(Locale.ROOT, " %6.2f sec. %s", v.value / 1000.0, v.key)
+ }
+ .join("\n"))
}
}
}
diff --git a/gradle/pylucene/pylucene.gradle b/build-tools/build-infra/src/main/groovy/lucene.misc.pylucene.gradle
similarity index 96%
rename from gradle/pylucene/pylucene.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.misc.pylucene.gradle
index 5ae8d7d9f4d..23253e5aecd 100644
--- a/gradle/pylucene/pylucene.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.misc.pylucene.gradle
@@ -21,7 +21,7 @@
*/
configure(rootProject.ext.mavenProjects, {
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
/**
* Collect the module's primary artifact and any runtime JARs it requires.
*/
@@ -37,4 +37,4 @@ configure(rootProject.ext.mavenProjects, {
into project.layout.buildDirectory.file("runtimeJars")
})
}
-})
\ No newline at end of file
+})
diff --git a/gradle/maven/maven-to-local-m2.gradle b/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-local-m2.gradle
similarity index 88%
rename from gradle/maven/maven-to-local-m2.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-local-m2.gradle
index d63e455fbc3..44efa9d6345 100644
--- a/gradle/maven/maven-to-local-m2.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-local-m2.gradle
@@ -19,12 +19,12 @@
// Configure on-demand maven publishing into ~/.m2 for developers' convenience.
configure(rootProject) {
- task mavenToLocal() {
- group "Distribution"
- description "Publish Lucene Maven artifacts to ~/.m2 repository."
+ tasks.register("mavenToLocal", {
+ group = "Distribution"
+ description = "Publish Lucene Maven artifacts to ~/.m2 repository."
dependsOn rootProject.ext.mavenProjects.collect {
it.tasks.matching { it.name == "publishJarsPublicationToMavenLocal" }
}
- }
-}
\ No newline at end of file
+ })
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-nexus-releases.gradle b/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-nexus-releases.gradle
new file mode 100644
index 00000000000..eb2d1e3d61a
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-nexus-releases.gradle
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+
+
+// Configure artifact push to apache nexus (releases repository).
+def apacheNexusReleasesRepository = "https://repository.apache.org/service/local/staging/deploy/maven2"
+
+// These access credentials must be passed by the release manager
+// (either on command-line, via the environment or via ~/.gradle.properties).
+Provider<String> asfNexusUsername = providers.gradleProperty("asfNexusUsername")
+ .orElse(providers.systemProperty("asfNexusUsername"))
+ .orElse(providers.environmentVariable("ASF_NEXUS_USERNAME"))
+
+Provider<String> asfNexusPassword = providers.gradleProperty("asfNexusPassword")
+ .orElse(providers.systemProperty("asfNexusPassword"))
+ .orElse(providers.environmentVariable("ASF_NEXUS_PASSWORD"))
+
+tasks.register("mavenToApacheReleases", {
+ group = "Distribution"
+ description = "Publish Lucene Maven artifacts to Apache Releases repository: ${apacheNexusReleasesRepository}"
+
+ dependsOn rootProject.ext.mavenProjects.collect {
+ it.tasks.matching { it.name == "publishSignedJarsPublicationToApacheReleasesRepository" }
+ }
+})
+
+def checkReleasesRepositoryPushPreconditions = tasks.register("checkReleasesRepositoryPushPreconditions", {
+ doFirst {
+ // Make sure we're pushing a release version. The release repository
+ // does not accept snapshots and returns cryptic errors upon trying.
+ if (rootProject.ext.snapshotBuild) {
+ throw new GradleException("ASF releases repository will not accept a snapshot version: ${rootProject.version}")
+ }
+
+ // Make sure access credentials have been passed.
+ if (!asfNexusUsername.isPresent() || !asfNexusPassword.isPresent()) {
+ throw new GradleException("asfNexusUsername or asfNexusPassword is empty: these are required to publish to " +
+ " ASF Nexus.")
+ }
+ }
+})
+
+configure(rootProject.ext.mavenProjects) { Project project ->
+ // Make sure any actual publication task is preceded by precondition checks.
+ tasks.matching { it.name ==~ /publish.+ToApacheReleasesRepository/ }.configureEach {
+ dependsOn checkReleasesRepositoryPushPreconditions
+ }
+
+ // Configure the release repository.
+ plugins.withType(PublishingPlugin).configureEach {
+ publishing {
+ repositories {
+ maven {
+ name = "ApacheReleases"
+ url = apacheNexusReleasesRepository
+
+ credentials {
+ username asfNexusUsername.getOrElse(null)
+ password asfNexusPassword.getOrElse(null)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-nexus-snapshots.gradle b/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-nexus-snapshots.gradle
new file mode 100644
index 00000000000..b477d4f9470
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.publications.maven-to-nexus-snapshots.gradle
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+
+// Configure artifact push to apache nexus (snapshots repository, CI job)
+def apacheNexusSnapshotsRepository = "https://repository.apache.org/content/repositories/snapshots"
+
+// These access credentials must be passed by the release manager
+// (either on command-line, via the environment or via ~/.gradle.properties).
+Provider<String> asfNexusUsername = providers.gradleProperty("asfNexusUsername")
+ .orElse(providers.systemProperty("asfNexusUsername"))
+ .orElse(providers.environmentVariable("ASF_NEXUS_USERNAME"))
+
+Provider<String> asfNexusPassword = providers.gradleProperty("asfNexusPassword")
+ .orElse(providers.systemProperty("asfNexusPassword"))
+ .orElse(providers.environmentVariable("ASF_NEXUS_PASSWORD"))
+
+tasks.register("mavenToApacheSnapshots", {
+ group = "Distribution"
+ description = "Publish Lucene Maven artifacts to Apache Snapshots repository: ${apacheNexusSnapshotsRepository}"
+
+ dependsOn rootProject.ext.mavenProjects.collect {
+ it.tasks.matching { it.name == "publishJarsPublicationToApacheSnapshotsRepository" }
+ }
+})
+
+def checkSnapshotsRepositoryPushPreconditions = tasks.register("checkSnapshotsRepositoryPushPreconditions", {
+ doFirst {
+ // Make sure we're pushing a snapshot version.
+ if (!rootProject.ext.snapshotBuild) {
+ throw new GradleException("ASF snapshots repository will not accept a non-snapshot version: ${rootProject.version}")
+ }
+
+ // Make sure access credentials have been passed.
+ if (!asfNexusUsername.isPresent() || !asfNexusPassword.isPresent()) {
+ throw new GradleException("asfNexusUsername or asfNexusPassword is empty: these are required to publish to " +
+ " ASF Nexus.")
+ }
+ }
+})
+
+configure(rootProject.ext.mavenProjects) { Project project ->
+ // Make sure any actual publication task is preceded by precondition checks.
+ tasks.matching { it.name ==~ /publish.+ToApacheSnapshotsRepository/ }.configureEach {
+ dependsOn checkSnapshotsRepositoryPushPreconditions
+ }
+
+ plugins.withType(PublishingPlugin).configureEach {
+ publishing {
+ repositories {
+ maven {
+ name = "ApacheSnapshots"
+ url = apacheNexusSnapshotsRepository
+
+ credentials {
+ username asfNexusUsername.getOrElse(null)
+ password asfNexusPassword.getOrElse(null)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/gradle/maven/publications-maven.gradle b/build-tools/build-infra/src/main/groovy/lucene.publications.maven.gradle
similarity index 53%
rename from gradle/maven/publications-maven.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.publications.maven.gradle
index cfaa4130d0d..2cab4702392 100644
--- a/gradle/maven/publications-maven.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.publications.maven.gradle
@@ -15,13 +15,75 @@
* limitations under the License.
*/
-// Configure projects for publishing Maven artifacts and set up repeatable metadata.
+/*
+ * This script configures aspects related to all project publications,
+ * this includes:
+ *
+ * - configuring maven artifacts,
+ * - setting up target maven repositories for publications to end up on,
+ * - configuring binary and source release artifacts,
+ * - other concerns related to publishing artifacts (signing, checksums).
+ */
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+//
+// An explicit list of projects to publish as Maven artifacts.
+//
+def mavenProjects = project(":lucene").subprojects.findAll {subproject ->
+ def excluded = [
+ // Exclude distribution assembly, tests & documentation.
+ ":lucene:distribution",
+ ":lucene:documentation",
+ // Exclude the parent container project for analysis modules (no artifacts).
+ ":lucene:analysis",
+ // Exclude the native module.
+ ":lucene:misc:native",
+ // Exclude test fixtures.
+ ":lucene:spatial-test-fixtures",
+ // Exclude JMH benchmarks.
+ ":lucene:benchmarks-jmh",
+ ]
+
+ // Exclude all subprojects that are modular test projects and those explicitly
+ // excluded above.
+ return !(subproject.path.endsWith(".tests")
+ || subproject.path.startsWith(":lucene:build-tools:")
+ || subproject.path in excluded)
+}
+
+// Make projects available to other scripts. Perhaps we should think of another way to do it.
+ext.set("mavenProjects", mavenProjects)
+
+
+// Optionally, switch to using an external GPG command, using it's configured gpg-agent for key management
+Provider<Boolean> useGpgOption = buildOptions.addBooleanOption("useGpg", "Use GPG for signing artifacts.", false)
+if (useGpgOption.get()) {
+ // Do this check before 'useGpgCmd()' (and once), otherwise gradle will fail with a confusing error about 'signatory.keyId'
+ //
+ // 'signatory.keyId' is an implementation detail of the SigningPlugin that it populates from 'signing.gnupg.keyName' when useGpgCmd()
+ // is used -- but does not explain in the error produced if 'signing.gnupg.keyName' is not set.
+ def propName = 'signing.gnupg.keyName'
+ if (!project.hasProperty(propName)) {
+ throw new GradleException("'$propName' project property must be set when using external GPG via 'useGpg', please see help/publishing.txt")
+ }
+
+ rootProject.allprojects {
+ plugins.withType(SigningPlugin).configureEach {
+ signing {
+ useGpgCmd()
+ }
+ }
+ }
+}
-configure(rootProject.ext.mavenProjects) { Project project ->
+configure(mavenProjects) { Project project ->
project.apply plugin: 'maven-publish'
project.apply plugin: 'signing'
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
// We have two types of publications: jars and signed jars.
publishing {
publications {
@@ -37,31 +99,27 @@ configure(rootProject.ext.mavenProjects) { Project project ->
// Each publication consists of the java components, source and javadoc artifacts.
// Add tasks to assemble source and javadoc JARs.
- task sourcesJar(type: Jar, dependsOn: classes) {
+ def sourcesJar = tasks.register("sourcesJar", Jar, {
+ dependsOn "classes"
archiveClassifier = 'sources'
from sourceSets.main.allJava
- }
+ })
- task javadocJar(type: Jar, dependsOn: javadoc) {
+ def javadocJar = tasks.register("javadocJar", Jar, {
+ dependsOn "javadoc"
archiveClassifier = 'javadoc'
from javadoc.destinationDir
- }
+ })
- // This moves pom metadata configuration after all the scripts of all projects
- // have been evaluated. This is required because we set artifact groups
- // and archivesName in other scripts and some of the properties below don't
- // accept lazy property providers (so everything must be in its final form).
- gradle.projectsEvaluated {
- publishing {
- publications.each { publication ->
- configure(publication) {
- from components.java
- groupId = project.group
- artifactId = project.base.archivesName.get()
-
- artifact sourcesJar
- artifact javadocJar
- }
+ publishing {
+ publications.each { publication ->
+ configure(publication) {
+ from components.java
+ groupId = project.group
+ artifactId = project.base.archivesName.get()
+
+ artifact sourcesJar
+ artifact javadocJar
}
}
}
@@ -85,8 +143,8 @@ configure(rootProject.ext.mavenProjects) { Project project ->
inceptionYear = "2000"
issueManagement {
- system = "JIRA"
- url = "https://issues.apache.org/jira/browse/LUCENE"
+ system = "github"
+ url = "https://github.com/apache/lucene/issues"
}
ciManagement {
@@ -132,10 +190,10 @@ configure(rootProject.ext.mavenProjects) { Project project ->
afterEvaluate {
configurations.matching { configuration ->
configuration.name in [
- "testFixturesApiElements",
- "testFixturesRuntimeElements"
+ "testFixturesApiElements",
+ "testFixturesRuntimeElements"
]
- }.all {
+ }.configureEach {
project.components.java.withVariantsFromConfiguration(it) { variant ->
variant.skip()
}
@@ -143,8 +201,14 @@ configure(rootProject.ext.mavenProjects) { Project project ->
}
// Hack: do not generate or publish gradle metadata files.
- tasks.withType(GenerateModuleMetadata) {
+ tasks.withType(GenerateModuleMetadata).configureEach {
enabled = false
}
}
+// Configure on-demand maven publishing into ~/.m2 for developers' convenience.
+plugins.apply('lucene.publications.maven-to-local-m2')
+
+// Configure ASF Nexus publications.
+plugins.apply('lucene.publications.maven-to-nexus-releases')
+plugins.apply('lucene.publications.maven-to-nexus-snapshots')
diff --git a/gradle/generation/antlr.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.antlr.gradle
similarity index 81%
rename from gradle/generation/antlr.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.antlr.gradle
index 729d039c5f9..ea68548dbd6 100644
--- a/gradle/generation/antlr.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.antlr.gradle
@@ -1,5 +1,3 @@
-import java.nio.file.Files
-
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -16,6 +14,7 @@ import java.nio.file.Files
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+import java.nio.file.Files
configure(project(":lucene:expressions")) {
configurations {
@@ -27,16 +26,16 @@ configure(project(":lucene:expressions")) {
}
task generateAntlrInternal() {
- description "Regenerate Javascript.g4"
- group "generation"
+ description = "Regenerate Javascript.g4"
+ group = "generation"
dependsOn configurations.antlr
def generatedPatterns = [
- "**/JavascriptBaseVisitor.java",
- "**/JavascriptLexer.java",
- "**/JavascriptParser.java",
- "**/JavascriptVisitor.java",
+ "**/JavascriptBaseVisitor.java",
+ "**/JavascriptLexer.java",
+ "**/JavascriptParser.java",
+ "**/JavascriptVisitor.java",
]
def sourceDir = "src/java/org/apache/lucene/expressions/js"
@@ -57,11 +56,13 @@ configure(project(":lucene:expressions")) {
ignoreExitValue false
args = [
- "-no-listener",
- "-visitor",
- "-package", "org.apache.lucene.expressions.js",
- "-o", tempOutput,
- inputFiles
+ "-no-listener",
+ "-visitor",
+ "-package",
+ "org.apache.lucene.expressions.js",
+ "-o",
+ tempOutput,
+ inputFiles
]
}
@@ -84,9 +85,12 @@ configure(project(":lucene:expressions")) {
def generateAntlr = wrapWithPersistentChecksums(
generateAntlrInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
- ])
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
+ ])
regenerate.dependsOn generateAntlr
}
diff --git a/gradle/generation/extract-jdk-apis.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.extract-jdk-apis.gradle
similarity index 83%
rename from gradle/generation/extract-jdk-apis.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.extract-jdk-apis.gradle
index e000ca1c3c3..69caf822662 100644
--- a/gradle/generation/extract-jdk-apis.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.extract-jdk-apis.gradle
@@ -15,14 +15,9 @@
* limitations under the License.
*/
-def resources = scriptResources(buildscript)
+def resources = rootProject.file("gradle/regenerate/extract-jdk-apis")
configure(project(":lucene:core")) {
- ext {
- apijars = layout.projectDirectory.dir("src/generated/jdk")
- mrjarJavaVersions = [ 24 ]
- }
-
plugins.withType(JavaPlugin) {
mrjarJavaVersions.each { jdkVersion ->
def task = tasks.create(name: "generateJdkApiJar${jdkVersion}", type: JavaExec) {
@@ -47,13 +42,13 @@ configure(project(":lucene:core")) {
mainClass = file("${resources}/ExtractJdkApis.java") as String
systemProperties = [
- 'user.timezone': 'UTC',
- 'file.encoding': 'UTF-8',
+ 'user.timezone': 'UTC',
+ 'file.encoding': 'UTF-8',
]
args = [
- rootProject.minJavaVersion.toString(),
- jdkVersion,
- apijars.file("jdk${jdkVersion}.apijar"),
+ rootProject.minJavaVersion.toString(),
+ jdkVersion,
+ apijars.file("jdk${jdkVersion}.apijar"),
]
}
diff --git a/gradle/generation/forUtil.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.forUtil.gradle
similarity index 73%
rename from gradle/generation/forUtil.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.forUtil.gradle
index b73c69b6f12..0d6057536b2 100644
--- a/gradle/generation/forUtil.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.forUtil.gradle
@@ -20,8 +20,8 @@
configure(project(":lucene:core")) {
task generateForUtilInternal() {
- description "Regenerate gen_ForUtil.py"
- group "generation"
+ description = "Regenerate gen_ForUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/codecs/lucene103")
def genScript = file("${genDir}/gen_ForUtil.py")
@@ -34,19 +34,22 @@ configure(project(":lucene:core")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForUtilInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForDeltaUtilInternal() {
- description "Regenerate gen_ForDeltaUtil.py"
- group "generation"
+ description = "Regenerate gen_ForDeltaUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/codecs/lucene103")
def genScript = file("${genDir}/gen_ForDeltaUtil.py")
@@ -59,23 +62,25 @@ configure(project(":lucene:core")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForDeltaUtilInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
-
}
configure(project(":lucene:backward-codecs")) {
task generateForUtil84Internal() {
- description "Regenerate gen_ForUtil.py"
- group "generation"
+ description = "Regenerate gen_ForUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene84")
def genScript = file("${genDir}/gen_ForUtil.py")
@@ -88,19 +93,22 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForUtil84Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForUtil90Internal() {
- description "Regenerate gen_ForUtil.py"
- group "generation"
+ description = "Regenerate gen_ForUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene90")
def genScript = file("${genDir}/gen_ForUtil.py")
@@ -113,19 +121,22 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForUtil90Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForUtil99Internal() {
- description "Regenerate gen_ForUtil.py"
- group "generation"
+ description = "Regenerate gen_ForUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene99")
def genScript = file("${genDir}/gen_ForUtil.py")
@@ -138,19 +149,22 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForUtil99Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForUtil912Internal() {
- description "Regenerate gen_ForUtil.py"
- group "generation"
+ description = "Regenerate gen_ForUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene912")
def genScript = file("${genDir}/gen_ForUtil.py")
@@ -163,19 +177,22 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForUtil912Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForDeltaUtil912Internal() {
- description "Regenerate gen_ForDeltaUtil.py"
- group "generation"
+ description = "Regenerate gen_ForDeltaUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene912")
def genScript = file("${genDir}/gen_ForDeltaUtil.py")
@@ -188,19 +205,22 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForDeltaUtil912Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForUtil101Internal() {
- description "Regenerate gen_ForUtil.py"
- group "generation"
+ description = "Regenerate gen_ForUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene101")
def genScript = file("${genDir}/gen_ForUtil.py")
@@ -213,19 +233,22 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForUtil101Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateForDeltaUtil101Internal() {
- description "Regenerate gen_ForDeltaUtil.py"
- group "generation"
+ description = "Regenerate gen_ForDeltaUtil.py"
+ group = "generation"
def genDir = file("src/java/org/apache/lucene/backward_codecs/lucene101")
def genScript = file("${genDir}/gen_ForDeltaUtil.py")
@@ -238,14 +261,16 @@ configure(project(":lucene:backward-codecs")) {
quietExec {
workingDir genDir
executable project.externalTool("python3")
- args = [ '-B', genScript ]
+ args = ['-B', genScript]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateForDeltaUtil101Internal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
}
-
diff --git a/build-tools/build-infra/src/main/groovy/lucene.regenerate.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.gradle
new file mode 100644
index 00000000000..42249e0b1a8
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.gradle
@@ -0,0 +1,284 @@
+/*
+ * 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 groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+import org.apache.commons.codec.digest.DigestUtils
+
+import java.util.function.Function
+
+// Create common 'regenerate' task sub-tasks can hook into.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+/**
+ * Compute all "checksummed" key-value pairs.
+ */
+def computeChecksummedEntries = { Task sourceTask ->
+ // An flat ordered map of key-value pairs.
+ Map<String, String> allEntries = new TreeMap<>()
+
+ // Make sure all input properties are either simple strings
+ // or closures returning simple strings.
+ //
+ // Don't overcomplicate things with other serializable types.
+ Map<String, Object> props = sourceTask.inputs.properties
+ props.forEach { key, val ->
+ // Handle closures and other lazy providers.
+ if (val instanceof Provider<?>) {
+ val = val.get()
+ }
+ if (val instanceof Closure<?>) {
+ val = val.call()
+ }
+
+ if (!(val instanceof String)) {
+ throw new GradleException("Input properties of wrapped tasks must all be " +
+ "strings: ${key} in ${sourceTask.name} is not.")
+ }
+ allEntries.put("property:" + key, (String) val)
+ }
+
+ // Collect all of task inputs/ output files and compute their checksums.
+ FileCollection allFiles = sourceTask.inputs.files + sourceTask.outputs.files
+
+ // Compute checksums for root-project relative paths
+ def digestUtils = new DigestUtils(DigestUtils.getSha1Digest())
+ allFiles.files.forEach { file ->
+ allEntries.put(
+ sourceTask.project.rootDir.relativePath(file),
+ file.exists() ? digestUtils.digestAsHex(file).trim() : "--")
+ }
+
+ return allEntries
+}
+
+ext {
+ /**
+ * Utility function to read a file, apply changes to its content and write it back.
+ */
+ modifyFile = { File path, Function<String, String> modify ->
+ Function<String, String> normalizeEols = { text -> text.replace("\r\n", "\n") }
+
+ String original = path.getText("UTF-8")
+ String modified = normalizeEols.apply(original)
+ modified = modify.apply(modified)
+ modified = normalizeEols.apply(modified)
+ if (!original.equals(modified)) {
+ path.write(modified, "UTF-8")
+ }
+ }
+}
+
+configure([
+ project(":lucene:analysis:common"),
+ project(":lucene:analysis:icu"),
+ project(":lucene:analysis:kuromoji"),
+ project(":lucene:analysis:nori"),
+ project(":lucene:backward-codecs"),
+ project(":lucene:core"),
+ project(":lucene:queryparser"),
+ project(":lucene:expressions"),
+ project(":lucene:test-framework"),
+]) {
+ tasks.register("regenerate", {
+ description = "Rerun any code or static data generation tasks."
+ group = "generation"
+ })
+
+ project.ext {
+ // This utility method implements the logic required for "persistent" incremental
+ // source-generating tasks. The idea is simple, the implementation quite complex.
+ //
+ // The idea is that, given source-generating task "sourceTaskInternal" (note the suffix),
+ // we create a bunch of other tasks that perform checksum generation, validation and
+ // source task skipping. For example, let's say we have a task 'genFooInternal";
+ // the following tasks would be created
+ //
+ // genFooChecksumLoad
+ // genFooChecksumSave
+ // genFooChecksumCheck (fails if checksums are inconsistent)
+ //
+ // and the following set of dependencies would be created (with additional
+ // constraints to run them in this particular order!).
+ //
+ // genFoo.dependsOn [genFooChecksumLoad, genFooInternal, genFooChecksumSave]
+ //
+ // Checksums are persisted and computed from sourceTask's inputs/outputs. If the
+ // persisted checksums are identical to the now-current checksums, the "internal" task
+ // is skipped (using onlyIf { false }).
+ //
+ // Implementation-wise things get complicated because gradle doesn't have the notion
+ // of "ordered" task execution with respect to task AND its dependencies (we can add
+ // constraints to each node in the execution graph but not node-and-dependencies).
+ //
+ // sourceTask - the task to wrap
+ // extraConfig - a map with extra (optional) configuration options.
+ // andThenTasks: any other tasks that should be scheduled to run after the internal task and
+ // before checksum calculation/ saving. spotless is a good example of this.
+ // ignoreWithSource: any other tasks that should be ignored if the internal task is ignored
+ // (checksums are identical)
+ // mustRunBefore: any tasks which should be scheduled to run after the internal task.
+ wrapWithPersistentChecksums = { Task sourceTask, Map<String, Object> extraConfig = [:] ->
+ if (!sourceTask.name.endsWith("Internal")) {
+ throw new GradleException("Wrapped task must follow the convention name of *Internal: ${sourceTask.name}")
+ }
+
+ String sourceTaskName = sourceTask.name.replaceAll('Internal$', '')
+
+ def toList = { value ->
+ if (value instanceof List) {
+ return value
+ } else if (value == null) {
+ return []
+ } else {
+ return [value]
+ }
+ }
+
+ List<Object> andThenTasks = toList(extraConfig.get("andThenTasks"))
+ List<Object> ignoreWithSource = toList(extraConfig.get("ignoreWithSource"))
+
+ // Schedule must-run-afters
+ List<Object> mustRunBefore = toList(extraConfig.get("mustRunBefore"))
+ // TODO: maybe ensure all task refs here are strings?
+ tasks.matching { it.name in mustRunBefore }.configureEach {
+ mustRunAfter sourceTask
+ }
+
+ // Create checksum-loader task.
+ Task checksumLoadTask = tasks.create("${sourceTaskName}ChecksumLoad", {
+ ext {
+ checksumMatch = true
+ }
+
+ doFirst {
+ // Current persisted task input/outputs (file checksums, properties)
+ ext.currentChecksums = computeChecksummedEntries(sourceTask)
+
+ // Load any previously written checksums
+ ext.savedChecksums = new TreeMap<>()
+ ext.checksumsFile = project.file("src/generated/checksums/${sourceTaskName}.json")
+ if (checksumsFile.exists()) {
+ savedChecksums.putAll(new JsonSlurper().parse(checksumsFile) as Map)
+ }
+
+ // Compare saved and current checksums for subsequent tasks.
+ ext.checksumMatch = (savedChecksums.equals(currentChecksums))
+ }
+ })
+
+ Task checksumCheckTask = tasks.create("${sourceTaskName}ChecksumCheck", {
+ dependsOn checksumLoadTask
+
+ doFirst {
+ if (!checksumLoadTask.checksumMatch) {
+ // This can be made prettier but leave it verbose for now:
+ Map<String, String> current = checksumLoadTask.currentChecksums
+ Map<String, String> expected = checksumLoadTask.savedChecksums
+
+ def same = current.intersect(expected)
+ current = current - same
+ expected = expected - same
+
+ throw new GradleException("Checksums mismatch for derived resources; you might have" +
+ " modified a generated resource (regenerate task: ${sourceTaskName}):\n" +
+ "Current:\n ${current.entrySet().join('\n ')}\n\n" +
+ "Expected:\n ${expected.entrySet().join('\n ')}\n\n" +
+ "Input files for this task are:\n " + sourceTask.inputs.files.join('\n ') + "\n\n" +
+ "Files generated by this task are:\n " + sourceTask.outputs.files.join('\n ')
+ )
+ }
+ }
+ })
+ check.dependsOn checksumCheckTask
+
+ Task checksumSaveTask = tasks.create("${sourceTaskName}ChecksumSave", {
+ dependsOn checksumLoadTask
+
+ doFirst {
+ File checksumsFile = checksumLoadTask.ext.checksumsFile
+ checksumsFile.parentFile.mkdirs()
+
+ // Recompute checksums after the task has completed and write them.
+ def updatedChecksums = computeChecksummedEntries(sourceTask)
+ checksumsFile.setText(
+ JsonOutput.prettyPrint(JsonOutput.toJson(new TreeMap<String, String>(updatedChecksums))), "UTF-8")
+
+ logger.warn("Updated generated file checksums for task ${sourceTask.path}.")
+ }
+ })
+
+ Task conditionalTask = tasks.create("${sourceTaskName}", {
+ def deps = [
+ checksumLoadTask,
+ sourceTask,
+ *andThenTasks,
+ checksumSaveTask
+ ].flatten()
+
+ dependsOn deps
+ mustRunInOrder deps
+
+ doFirst {
+ if (checksumLoadTask.checksumMatch && !sourceTask.didWork) {
+ logger.lifecycle("Checksums consistent with sources, skipping task: ${sourceTask.path}")
+ }
+ }
+ })
+
+ // Load checksums before the source task executes, otherwise it's always ignored.
+ project.afterEvaluate {
+ resolveTaskRefs([sourceTask, *ignoreWithSource]).each { t ->
+ t.configure {
+ dependsOn checksumLoadTask
+ }
+ }
+ }
+
+ // Copy the description and group from the source task.
+ project.afterEvaluate {
+ conditionalTask.group sourceTask.group
+ conditionalTask.description sourceTask.description + " (if sources changed)"
+
+ // Hide low-level tasks from help.
+ sourceTask.group = null
+ sourceTask.description sourceTask.description + " (low-level)"
+ }
+
+ // Set conditional execution only if checksum mismatch occurred.
+ if (!gradle.startParameter.isRerunTasks()) {
+ project.afterEvaluate {
+ resolveTaskRefs([
+ sourceTask,
+ *ignoreWithSource,
+ checksumSaveTask
+ ]).each { t ->
+ t.configure {
+ logger.info("Making " + t.name + " run only if " + checksumLoadTask.name + " indicates changes")
+ onlyIf { !checksumLoadTask.checksumMatch }
+ }
+ }
+ }
+ }
+
+ return conditionalTask
+ }
+ }
+}
diff --git a/gradle/generation/icu.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.icu.gradle
similarity index 87%
rename from gradle/generation/icu.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.icu.gradle
index c6c7c71cf7a..64ab7f58193 100644
--- a/gradle/generation/icu.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.icu.gradle
@@ -1,6 +1,3 @@
-import org.apache.tools.ant.taskdefs.condition.Os
-import java.nio.file.Files
-
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -18,7 +15,10 @@ import java.nio.file.Files
* limitations under the License.
*/
-def resources = scriptResources(buildscript)
+import org.apache.tools.ant.taskdefs.condition.Os
+import java.nio.file.Files
+
+def resources = rootProject.file("gradle/regenerate/icu")
/*
* Regenerates ICU-related data files.
@@ -34,10 +34,13 @@ def resources = scriptResources(buildscript)
configure(rootProject) {
configurations {
icu_current
+ groovy
}
dependencies {
icu_current deps.icu4j
+ // Use a newer groovy that doesn't have illegal reflective accesses.
+ groovy deps.groovy
}
}
@@ -96,28 +99,28 @@ configure(project(":lucene:analysis:icu")) {
ignoreExitValue false
workingDir utr30DataDir
args = [
- "release-${icu4jVersion.replace(".", "-")}"
+ "release-${icu4jVersion.replace(".", "-")}"
]
}
project.quietExec {
executable gennorm
args = [
- "-v",
- "-s",
- utr30DataDir,
- "-o",
- "${buildDir}/utr30.tmp",
- *(inputFiles.collect { it.name })
+ "-v",
+ "-s",
+ utr30DataDir,
+ "-o",
+ "${buildDir}/utr30.tmp",
+ *(inputFiles.collect { it.name })
]
}
project.quietExec {
executable icupkg
args = [
- "-tb",
- "${buildDir}/utr30.tmp",
- outputFile
+ "-tb",
+ "${buildDir}/utr30.tmp",
+ outputFile
]
}
}
@@ -145,17 +148,17 @@ configure(project(":lucene:analysis:icu")) {
ignoreExitValue false
enableAssertions true
- args = [ sourceDir, targetDir ]
+ args = [sourceDir, targetDir]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(genUtr30DataFilesInternal, [
ignoreWithSource: icuCompileTask,
- mustRunBefore: [ "compileJava" ]
+ mustRunBefore: ["compileJava"]
])
regenerate.dependsOn wrapWithPersistentChecksums(genRbbiInternal, [
- mustRunBefore: [ "compileJava" ]
+ mustRunBefore: ["compileJava"]
])
task compileIcuWindows() {
@@ -178,7 +181,6 @@ configure(project(":lucene:analysis:icu")) {
into icuBuildDir
from zipTree(icuBinZip)
}
-
}
}
@@ -208,8 +210,8 @@ configure(project(":lucene:analysis:icu")) {
executable "tar"
workingDir icuBuildDir
args = [
- "-zxf",
- icuSrcTgz
+ "-zxf",
+ icuSrcTgz
]
}
@@ -221,9 +223,9 @@ configure(project(":lucene:analysis:icu")) {
environment("CFLAGS", "-O0")
environment("CXXFLAGS", "-O0")
args = [
- "configure",
- "--prefix=${icuSrcDir}",
- "--enable-rpath"
+ "configure",
+ "--prefix=${icuSrcDir}",
+ "--enable-rpath"
]
}
@@ -231,7 +233,7 @@ configure(project(":lucene:analysis:icu")) {
executable "make"
workingDir icuSrcDir
args = [
- "-j${propertyOrDefault('tests.jvms', '4')}"
+ "-j${buildOptions['tests.jvms'].get()}"
]
}
@@ -240,9 +242,7 @@ configure(project(":lucene:analysis:icu")) {
project.quietExec {
executable "./derb"
workingDir icuBinDir
- args = [
- "-V"
- ]
+ args = ["-V"]
}
}
}
@@ -269,17 +269,21 @@ configure(project(":lucene:analysis:common")) {
classpath icuConfig, rootProject.configurations.groovy
args = [
- "--encoding", "UTF-8",
- file("${resources}/GenerateUnicodeProps.groovy"),
- outputFile
+ "--encoding",
+ "UTF-8",
+ file("${resources}/GenerateUnicodeProps.groovy"),
+ outputFile
]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateUnicodePropsInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
}
@@ -303,16 +307,20 @@ configure(project(":lucene:core")) {
classpath icuConfig, rootProject.configurations.groovy
args = [
- "--encoding", "UTF-8",
- file("${resources}/GenerateCaseFolding.groovy"),
- outputFile
+ "--encoding",
+ "UTF-8",
+ file("${resources}/GenerateCaseFolding.groovy"),
+ outputFile
]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateUnicodePropsInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
}
diff --git a/gradle/generation/javacc.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.javacc.gradle
similarity index 89%
rename from gradle/generation/javacc.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.javacc.gradle
index 559d07fc6d9..60f6e4fc3c7 100644
--- a/gradle/generation/javacc.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.javacc.gradle
@@ -1,6 +1,3 @@
-import java.nio.charset.Charset
-import java.util.function.Function
-
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -18,6 +15,9 @@ import java.util.function.Function
* limitations under the License.
*/
+import java.nio.charset.Charset
+import java.util.function.Function
+
// This adds javacc generation support.
configure(rootProject) {
@@ -29,12 +29,12 @@ configure(rootProject) {
javacc deps.javacc
}
- task javacc() {
- description "Regenerate sources for corresponding javacc grammar files."
- group "generation"
+ tasks.register("javacc", {
+ description = "Regenerate sources for corresponding javacc grammar files."
+ group = "generation"
dependsOn allprojects.collect { prj -> prj.tasks.withType(JavaCCTask) }
- }
+ })
}
def commonCleanups = { FileTree generatedFiles ->
@@ -68,7 +68,7 @@ def commonCleanups = { FileTree generatedFiles ->
/package (.+)/,
'''
package $1
- import org.apache.lucene.queryparser.charstream.CharStream;
+ import org.apache.lucene.queryparser.charstream.CharStream;
'''.trim())
// Eliminates redundant cast message.
text = text.replace(
@@ -88,8 +88,8 @@ def commonCleanups = { FileTree generatedFiles ->
configure(project(":lucene:queryparser")) {
task javaccParserClassicInternal(type: JavaCCTask) {
- description "Regenerate classic query parser from lucene/queryparser/classic/QueryParser.jj"
- group "generation"
+ description = "Regenerate classic query parser from lucene/queryparser/classic/QueryParser.jj"
+ group = "generation"
javaccFile = file('src/java/org/apache/lucene/queryparser/classic/QueryParser.jj')
@@ -125,8 +125,8 @@ configure(project(":lucene:queryparser")) {
}
task javaccParserSurroundInternal(type: JavaCCTask) {
- description "Regenerate surround query parser from lucene/queryparser/surround/parser/QueryParser.jj"
- group "generation"
+ description = "Regenerate surround query parser from lucene/queryparser/surround/parser/QueryParser.jj"
+ group = "generation"
javaccFile = file('src/java/org/apache/lucene/queryparser/surround/parser/QueryParser.jj')
@@ -150,8 +150,8 @@ configure(project(":lucene:queryparser")) {
}
task javaccParserFlexibleInternal(type: JavaCCTask) {
- description "Regenerate flexible query parser from queryparser/flexible/standard/parser/StandardSyntaxParser.jj"
- group "generation"
+ description = "Regenerate flexible query parser from queryparser/flexible/standard/parser/StandardSyntaxParser.jj"
+ group = "generation"
javaccFile = file('src/java/org/apache/lucene/queryparser/flexible/standard/parser/StandardSyntaxParser.jj')
@@ -168,7 +168,7 @@ configure(project(":lucene:queryparser")) {
text = text.replace(
"package org.apache.lucene.queryparser.flexible.standard.parser;", '''\
package org.apache.lucene.queryparser.flexible.standard.parser;
-
+
import org.apache.lucene.queryparser.flexible.messages.*;
import org.apache.lucene.queryparser.flexible.core.*;
import org.apache.lucene.queryparser.flexible.core.messages.*;
@@ -178,7 +178,7 @@ configure(project(":lucene:queryparser")) {
text = text.replaceAll(
/(?s)[ ]*public ParseException\(Token currentTokenVal[^}]+[}]/, '''\
public ParseException(Token currentTokenVal,
- int[][] expectedTokenSequencesVal, String[] tokenImageVal)
+ int[][] expectedTokenSequencesVal, String[] tokenImageVal)
{
super(new MessageImpl(QueryParserMessages.INVALID_SYNTAX, initialise(
currentTokenVal, expectedTokenSequencesVal, tokenImageVal)));
@@ -190,7 +190,7 @@ configure(project(":lucene:queryparser")) {
text = text.replaceAll(
/(?s)[ ]*public ParseException\(String message\)[^}]+[}]/, '''\
- public ParseException(Message message)
+ public ParseException(Message message)
{
super(message);
}
@@ -198,7 +198,7 @@ configure(project(":lucene:queryparser")) {
text = text.replaceAll(
/(?s)[ ]*public ParseException\(\)[^}]+[}]/, '''\
- public ParseException()
+ public ParseException()
{
super(new MessageImpl(QueryParserMessages.INVALID_SYNTAX, "Error"));
}
@@ -229,12 +229,15 @@ configure(project(":lucene:queryparser")) {
}
task javacc() {
- description "Regenerate query parsers (javacc syntax definitions)."
- group "generation"
+ description = "Regenerate query parsers (javacc syntax definitions)."
+ group = "generation"
def extraConfig = [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
]
dependsOn wrapWithPersistentChecksums(javaccParserClassicInternal, extraConfig),
@@ -242,7 +245,7 @@ configure(project(":lucene:queryparser")) {
wrapWithPersistentChecksums(javaccParserFlexibleInternal, extraConfig)
}
- regenerate.dependsOn javacc
+ regenerate.dependsOn "javacc"
}
// We always regenerate, no need to declare outputs.
@@ -265,12 +268,12 @@ class JavaCCTask extends DefaultTask {
def baseName = javaccFile.name.replace(".jj", "")
return [
- project.file("${baseDir}/${baseName}.java"),
- project.file("${baseDir}/${baseName}Constants.java"),
- project.file("${baseDir}/${baseName}TokenManager.java"),
- project.file("${baseDir}/ParseException.java"),
- project.file("${baseDir}/Token.java"),
- project.file("${baseDir}/TokenMgrError.java")
+ project.file("${baseDir}/${baseName}.java"),
+ project.file("${baseDir}/${baseName}Constants.java"),
+ project.file("${baseDir}/${baseName}TokenManager.java"),
+ project.file("${baseDir}/ParseException.java"),
+ project.file("${baseDir}/Token.java"),
+ project.file("${baseDir}/TokenMgrError.java")
]
}
@@ -305,8 +308,8 @@ class JavaCCTask extends DefaultTask {
main = "org.javacc.parser.Main"
args += [
- "-OUTPUT_DIRECTORY=${tempDir}",
- javaccFile
+ "-OUTPUT_DIRECTORY=${tempDir}",
+ javaccFile
]
}
diff --git a/gradle/generation/jflex.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.jflex.gradle
similarity index 89%
rename from gradle/generation/jflex.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.jflex.gradle
index 2729f2a10ff..8b9c1dadb73 100644
--- a/gradle/generation/jflex.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.jflex.gradle
@@ -29,7 +29,7 @@ configure(rootProject) {
}
}
-def resources = scriptResources(buildscript)
+def resources = rootProject.file("gradle/regenerate/jflex")
def skeletonDefault = file("${resources}/skeleton.default.txt")
def skeletonNoBufferExpansion = file("${resources}/skeleton.disable.buffer.expansion.txt")
@@ -47,13 +47,16 @@ configure(project(":lucene:core")) {
encoding: "UTF-8",
token: "private static final int ZZ_BUFFERSIZE =",
value: "private int ZZ_BUFFERSIZE ="
- )
+ )
}
}
def generateStandardTokenizer = wrapWithPersistentChecksums(generateStandardTokenizerInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
regenerate.dependsOn generateStandardTokenizer
@@ -83,9 +86,9 @@ configure(project(":lucene:analysis:common")) {
ignoreExitValue false
args = [
- tldZones,
- tmpJflexMacro,
- tmpTldList
+ tldZones,
+ tmpJflexMacro,
+ tmpTldList
]
}
@@ -148,13 +151,16 @@ configure(project(":lucene:analysis:common")) {
encoding: "UTF-8",
token: "private static final int ZZ_BUFFERSIZE =",
value: "private int ZZ_BUFFERSIZE ="
- )
+ )
}
}
def generateUAX29URLEmailTokenizer = wrapWithPersistentChecksums(generateUAX29URLEmailTokenizerInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
// UAX29URLEmailTokenizerImpl.jflex includes: ASCIITLD.jflex
@@ -179,9 +185,10 @@ configure(project(":lucene:analysis:common")) {
executable = project.externalTool("python3")
workingDir = target.parentFile
args += [
- "-B", // don't write any bytecode cache
- script,
- target
+ "-B",
+ // don't write any bytecode cache
+ script,
+ target
]
}
@@ -189,7 +196,7 @@ configure(project(":lucene:analysis:common")) {
file: target,
encoding: "UTF-8",
eol: "lf"
- )
+ )
}
}
@@ -205,8 +212,11 @@ configure(project(":lucene:analysis:common")) {
}
def extraConfig = [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
]
def generateHTMLStripCharFilter = wrapWithPersistentChecksums(generateHTMLStripCharFilterInternal, extraConfig)
@@ -262,9 +272,10 @@ class JFlexTask extends DefaultTask {
main = "jflex.Main"
args += [
- "-nobak",
- "--quiet",
- "--encoding", "UTF-8",
+ "-nobak",
+ "--quiet",
+ "--encoding",
+ "UTF-8",
]
if (heapSize) {
@@ -272,12 +283,16 @@ class JFlexTask extends DefaultTask {
}
if (skeleton) {
- args += ["--skel", skeleton.absolutePath]
+ args += [
+ "--skel",
+ skeleton.absolutePath
+ ]
}
args += [
- "-d", target.parentFile.absolutePath,
- jflexFile
+ "-d",
+ target.parentFile.absolutePath,
+ jflexFile
]
}
@@ -286,17 +301,17 @@ class JFlexTask extends DefaultTask {
// you can't "stack" SuppressWarnings annotations, jflex adds its own, this is the only way
// https://github.com/jflex-de/jflex/issues/762
project.ant.replace(
- file: target,
- encoding: "UTF-8",
- token: 'SuppressWarnings("fallthrough")',
- value: 'SuppressWarnings({"fallthrough","unused"})'
- )
+ file: target,
+ encoding: "UTF-8",
+ token: 'SuppressWarnings("fallthrough")',
+ value: 'SuppressWarnings({"fallthrough","unused"})'
+ )
// Correct line endings for Windows.
project.ant.fixcrlf(
file: target,
encoding: "UTF-8",
eol: "lf"
- )
+ )
}
}
diff --git a/gradle/generation/kuromoji.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.kuromoji.gradle
similarity index 82%
rename from gradle/generation/kuromoji.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.kuromoji.gradle
index a5aa5fbd604..2b4d023ca02 100644
--- a/gradle/generation/kuromoji.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.kuromoji.gradle
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+import de.undercouch.gradle.tasks.download.Download
// This downloads and compiles Kuromoji dictionaries.
@@ -30,11 +31,9 @@ def recompileDictionary(project, dictionaryName, Closure closure) {
}
configure(project(":lucene:analysis:kuromoji")) {
- apply plugin: deps.plugins.undercouch.download.get().pluginId
-
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
project.ext {
- targetDir = file("src/resources")
+ targetDir = project.file("src/resources")
}
task deleteDictionaryData() {
@@ -73,24 +72,21 @@ configure(project(":lucene:analysis:kuromoji")) {
// Apply patch via local git.
project.quietExec {
workingDir = unpackedDir
- // TODO: Uwe says: better use jgit to apply patch, this is not portable!!!
- // Dawid answers: (LUCENE-10215) jgit's patch was broken - would not handle binary patches
- // Seems like this has been fixed: https://gerrit.googlesource.com/jgit/+/10ac4499115965ff10e547a0632c89873a06cf91
executable "git"
args += [
- "apply",
- file("src/tools/patches/Noun.proper.csv.patch").absolutePath
+ "apply",
+ project.file("src/tools/patches/Noun.proper.csv.patch").absolutePath
]
}
// Compile the dictionary
recompileDictionary(project, dictionaryName, {
args += [
- "ipadic",
- unpackedDir,
- targetDir,
- "euc-jp",
- false
+ "ipadic",
+ unpackedDir,
+ targetDir,
+ "euc-jp",
+ false
]
})
}
@@ -122,11 +118,11 @@ configure(project(":lucene:analysis:kuromoji")) {
// Compile the dictionary
recompileDictionary(project, dictionaryName, {
args += [
- "ipadic",
- unpackedDir,
- targetDir,
- "euc-jp",
- false
+ "ipadic",
+ unpackedDir,
+ targetDir,
+ "euc-jp",
+ false
]
})
}
diff --git a/gradle/generation/moman.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.moman.gradle
similarity index 82%
rename from gradle/generation/moman.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.moman.gradle
index de80705eefa..69eb5cf2109 100644
--- a/gradle/generation/moman.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.moman.gradle
@@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-apply plugin: deps.plugins.undercouch.download.get().pluginId
+import de.undercouch.gradle.tasks.download.Download
-def resources = scriptResources(buildscript)
+def resources = rootProject.file("gradle/regenerate/moman")
configure(project(":lucene:core")) {
ext {
@@ -42,13 +42,16 @@ configure(project(":lucene:core")) {
def targetDir = file("src/java/org/apache/lucene/util/packed")
def templateFiles = [
- file("${resources}/gen_BulkOperation.py"),
- file("${resources}/gen_Packed64SingleBlock.py")
+ file("${resources}/gen_BulkOperation.py"),
+ file("${resources}/gen_Packed64SingleBlock.py")
]
inputs.property("source", momanSource)
inputs.files templateFiles
- outputs.files fileTree(dir: targetDir, includes: ["Packed64SingleBlock.java", "BulkOperation*.java"])
+ outputs.files fileTree(dir: targetDir, includes: [
+ "Packed64SingleBlock.java",
+ "BulkOperation*.java"
+ ])
doLast {
templateFiles.each { prog ->
@@ -65,7 +68,7 @@ configure(project(":lucene:core")) {
includes: 'Packed64SingleBlock.java, BulkOperation*.java',
encoding: 'UTF-8',
eol: 'lf'
- )
+ )
}
}
@@ -84,11 +87,13 @@ configure(project(":lucene:core")) {
quietExec {
workingDir targetDir
executable project.externalTool("python3")
- args = ['-B',
- templateFile.toString(),
- num,
- transpose,
- "${momanDir}/finenight/python"]
+ args = [
+ '-B',
+ templateFile.toString(),
+ num,
+ transpose,
+ "${momanDir}/finenight/python"
+ ]
}
}
}
@@ -97,7 +102,7 @@ configure(project(":lucene:core")) {
includes: '*ParametricDescription.java',
encoding: 'UTF-8',
eol: 'lf'
- )
+ )
}
}
@@ -106,8 +111,11 @@ configure(project(":lucene:core")) {
group "generation"
def extraConfig = [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
]
dependsOn wrapWithPersistentChecksums(utilGenPackedInternal, extraConfig)
diff --git a/gradle/generation/nori.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.nori.gradle
similarity index 91%
rename from gradle/generation/nori.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.nori.gradle
index 596d09b6161..90c75f635bd 100644
--- a/gradle/generation/nori.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.nori.gradle
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+import de.undercouch.gradle.tasks.download.Download
// This downloads and compiles Nori dictionaries.
@@ -30,11 +31,9 @@ def recompileDictionary(project, dictionaryName, Closure closure) {
}
configure(project(":lucene:analysis:nori")) {
- apply plugin: deps.plugins.undercouch.download.get().pluginId
-
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
project.ext {
- targetDir = file("src/resources")
+ targetDir = project.file("src/resources")
}
task deleteDictionaryData() {
@@ -73,10 +72,10 @@ configure(project(":lucene:analysis:nori")) {
// Compile the dictionary
recompileDictionary(project, dictionaryName, {
args += [
- unpackedDir,
- targetDir,
- "utf-8",
- false
+ unpackedDir,
+ targetDir,
+ "utf-8",
+ false
]
})
}
diff --git a/gradle/generation/snowball.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.snowball.gradle
similarity index 84%
rename from gradle/generation/snowball.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.snowball.gradle
index 86398b5129f..acbf8bcf700 100644
--- a/gradle/generation/snowball.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.snowball.gradle
@@ -14,12 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+import de.undercouch.gradle.tasks.download.Download
import org.apache.tools.ant.taskdefs.condition.Os
-def resources = scriptResources(buildscript)
-
-apply plugin: deps.plugins.undercouch.download.get().pluginId
+def resources = rootProject.file("gradle/regenerate/snowball")
configure(project(":lucene:analysis:common")) {
ext {
@@ -74,16 +72,16 @@ configure(project(":lucene:analysis:common")) {
// runs shell script to regenerate stemmers, base stemming subclasses, test data, and stopwords.
task snowballInternal() {
- description "Regenerate snowball stemmers."
- group "generation"
+ description = "Regenerate snowball stemmers."
+ group = "generation"
inputs.files fileTree(
dir: "src/java/org/tartarus/snowball",
include: [
- "Among.java",
- "SnowballStemmer.java",
- "SnowballProgram.java",
- "ext/*Stemmer.java"
+ "Among.java",
+ "SnowballStemmer.java",
+ "SnowballProgram.java",
+ "ext/*Stemmer.java"
])
inputs.files fileTree(
@@ -103,15 +101,26 @@ configure(project(":lucene:analysis:common")) {
doFirst {
project.quietExec {
executable "bash"
- args = [snowballScript, snowballStemmerDir, snowballWebsiteDir, projectDir]
+ args = [
+ snowballScript,
+ snowballStemmerDir,
+ snowballWebsiteDir,
+ projectDir
+ ]
}
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(snowballInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- ignoreWithSource: [downloadSnowballStemmers, downloadSnowballWebsite],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ ignoreWithSource: [
+ downloadSnowballStemmers,
+ downloadSnowballWebsite
+ ],
+ mustRunBefore: ["compileJava"]
])
}
diff --git a/gradle/generation/unicode-test-classes.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.unicode-test-classes.gradle
similarity index 87%
rename from gradle/generation/unicode-test-classes.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.regenerate.unicode-test-classes.gradle
index 0bf25aa190d..0c841a945e8 100644
--- a/gradle/generation/unicode-test-classes.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.regenerate.unicode-test-classes.gradle
@@ -37,15 +37,19 @@ configure(project(":lucene:test-framework")) {
workingDir genDir
executable project.externalTool("perl")
args = [
- genScript,
- "-v", unicodeVersion
+ genScript,
+ "-v",
+ unicodeVersion
]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateEmojiTokenizationTestInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
task generateJavaUnicodeWordBreakTestInternal() {
@@ -67,15 +71,19 @@ configure(project(":lucene:test-framework")) {
workingDir genDir
executable project.externalTool("perl")
args = [
- genScript,
- "-v", unicodeVersion
+ genScript,
+ "-v",
+ unicodeVersion
]
}
}
}
regenerate.dependsOn wrapWithPersistentChecksums(generateJavaUnicodeWordBreakTestInternal, [
- andThenTasks: ["spotlessJava", "spotlessJavaApply"],
- mustRunBefore: [ "compileJava" ]
+ andThenTasks: [
+ "spotlessJava",
+ "spotlessJavaApply"
+ ],
+ mustRunBefore: ["compileJava"]
])
}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.root-project.check-environment.gradle b/build-tools/build-infra/src/main/groovy/lucene.root-project.check-environment.gradle
new file mode 100644
index 00000000000..5e572eac878
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.root-project.check-environment.gradle
@@ -0,0 +1,88 @@
+/*
+ * 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 checks that we're running the desired version of Gradle and
+// that the JVM is supported.
+
+import org.gradle.util.GradleVersion
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+String expectedGradleVersion = deps.versions.minGradle.get()
+
+wrapper {
+ distributionType = Wrapper.DistributionType.BIN
+ gradleVersion = expectedGradleVersion
+}
+
+JavaVersion currentJavaVersion = JavaVersion.current()
+JavaVersion minJavaVersion = JavaVersion.toVersion(deps.versions.minJava.get())
+
+if (currentJavaVersion < minJavaVersion) {
+ throw new GradleException("At least Java ${minJavaVersion} is required, you are running Java ${currentJavaVersion} "
+ + "[${System.getProperty('java.vm.name')} ${System.getProperty('java.vm.version')}]")
+}
+
+if (Runtime.version().pre().isPresent()) {
+ throw new GradleException("You are running Gradle with an EA version of Java - this is not supported. "
+ + "To test Lucene compatibility with EA or pre-release versions, see this help guide: " +
+ " './gradlew helpJvms'. Detected Java version: "
+ + "[${System.getProperty('java.vm.name')} ${System.getProperty('java.vm.version')}]")
+}
+
+//
+// Skip this check if we're regenerating the wrapper.
+//
+if (!gradle.startParameter.taskNames.contains("wrapper")) {
+ GradleVersion currentGradleVersion = GradleVersion.current()
+ if (currentGradleVersion != GradleVersion.version(expectedGradleVersion)) {
+ if (currentGradleVersion.baseVersion == GradleVersion.version(expectedGradleVersion).baseVersion) {
+ logger.warn("Gradle ${expectedGradleVersion} is required but base version of this gradle matches, proceeding (" +
+ "this gradle is ${currentGradleVersion}).")
+ } else {
+ throw new GradleException("Gradle ${expectedGradleVersion} is required (hint: use the ./gradlew script), " +
+ "this gradle is ${currentGradleVersion}.")
+ }
+ }
+}
+
+//
+// Register this utility task on the root project.
+//
+tasks.register("checkJdkInternalsExportedToGradle", {
+ doFirst {
+ def jdkCompilerModule = ModuleLayer.boot().findModule("jdk.compiler").orElseThrow()
+ def gradleModule = getClass().module
+ def internalsExported = [
+ "com.sun.tools.javac.api",
+ "com.sun.tools.javac.file",
+ "com.sun.tools.javac.parser",
+ "com.sun.tools.javac.tree",
+ "com.sun.tools.javac.util"
+ ].stream()
+ .allMatch({ pkg -> jdkCompilerModule.isExported(pkg, gradleModule) })
+
+ if (!internalsExported) {
+ throw new GradleException(
+ "Certain gradle tasks and plugins require access to jdk.compiler" +
+ " internals, your gradle.properties might have just been generated or could be" +
+ " out of sync (see gradle/template.gradle.properties)")
+ }
+ }
+})
diff --git a/build-tools/build-infra/src/main/groovy/lucene.root-project.setup.gradle b/build-tools/build-infra/src/main/groovy/lucene.root-project.setup.gradle
new file mode 100644
index 00000000000..e140c1593b7
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.root-project.setup.gradle
@@ -0,0 +1,256 @@
+/*
+ * 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.buildoptions.BuildOptionValueSource
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsPlugin
+import com.carrotsearch.gradle.buildinfra.environment.GitInfoPlugin
+import com.carrotsearch.randomizedtesting.SeedUtils
+
+import java.time.ZonedDateTime
+import java.time.format.DateTimeFormatter
+
+// Prepare the root project and some global infrastructure.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+//
+// Register these plugins early.
+//
+plugins.apply(GitInfoPlugin)
+allprojects {
+ plugins.apply(BuildOptionsPlugin)
+}
+
+//
+// Figure out project version based on the base version and, suffix (or overrides of these options).
+//
+Provider<String> versionBase = buildOptions.addOption("version.base", "Base Lucene version")
+Provider<String> versionSuffix = buildOptions.addOption("version.suffix", "Appends project version suffix to 'version.base'.", "SNAPSHOT")
+Provider<String> versionProvider = buildOptions.addOption("version.release", "Lucene project version.",
+ versionSuffix
+ .map { suffix ->
+ versionBase.get() + "-" + suffix
+ }
+ .orElse(versionBase))
+
+String luceneVersion = versionProvider.get()
+rootProject.version = luceneVersion
+
+//
+// Expose parts of the final project version to the build. We can't use Runtime.Version, sadly.
+//
+ext {
+ // "base" version is stripped of the qualifier. Compute it because somebody might have passed
+ // -Pversion.release=x.y.z directly.
+ baseVersion = {
+ def m = (luceneVersion =~ /^(\d+\.\d+\.\d+)(-(.+))?/)
+ if (!m) {
+ throw new GradleException("Can't strip version to just x.y.z: " + rootProject.version)
+ }
+ return m[0][1]
+ }()
+ // "majorVersion" is an integer with just the major version. Compute it.
+ majorVersion = {
+ def m = (version =~ /^(\d+)\.\d+\.\d+(-(.+))?/)
+ if (!m) {
+ throw new GradleException("Can't strip version to just major version: " + rootProject.version)
+ }
+ return m[0][1] as int
+ }()
+
+ // snapshot build marker used in scripts.
+ snapshotBuild = luceneVersion.contains("SNAPSHOT")
+
+ // detect if we run in CI environment by looking at existence of env vars:
+ // "CI": Github (https://docs.github.com/en/actions/learn-github-actions/environment-variables)
+ // anything starting with "JENKINS_" or "HUDSON_": Jenkins/Hudson (https://jenkins.thetaphi.de/env-vars.html/)
+ isCIBuild = System.getenv().keySet().find { it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/ } != null
+
+ // Minimum Java version required to compile and run Lucene.
+ minJavaVersion = JavaVersion.toVersion(deps.versions.minJava.get())
+
+ // Build timestamp.
+ def tstamp = ZonedDateTime.now()
+ buildDate = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(tstamp)
+ buildTime = DateTimeFormatter.ofPattern("HH:mm:ss").format(tstamp)
+ buildYear = DateTimeFormatter.ofPattern("yyyy").format(tstamp)
+}
+
+//
+// Set certain root project properties eagerly so that plugins
+// and scripts have them available.
+//
+ext {
+ isIdea = Boolean.parseBoolean(System.getProperty("idea.active", "false"))
+ isIdeaSync = Boolean.parseBoolean(System.getProperty("idea.sync.active", "false"))
+ isIdeaBuild = (isIdea && !isIdeaSync)
+}
+
+ext {
+ // JDK versions where the vector module is still incubating;
+ // also change this in extractor tool: ExtractForeignAPI
+ vectorIncubatorJavaVersions = [
+ JavaVersion.VERSION_21,
+ JavaVersion.VERSION_22,
+ JavaVersion.VERSION_23,
+ JavaVersion.VERSION_24
+ ] as Set
+}
+
+// Pick the "root" seed from which everything else that is randomized is derived.
+Provider<String> rootSeedOption = buildOptions.addOption("tests.seed", "The \"root\" randomization seed for options and test parameters.", provider {
+ return String.format("%08X", new Random().nextLong())
+})
+ext {
+ rootSeed = rootSeedOption.get()
+ rootSeedUserProvided = buildOptions.getOption("tests.seed").getValue().get().source() == BuildOptionValueSource.COMPUTED_VALUE
+ rootSeedLong = SeedUtils.parseSeedChain(rootSeed)[0]
+}
+allprojects {
+ ext {
+ projectSeedLong = rootProject.rootSeedLong ^ project.path.hashCode()
+ }
+}
+
+tasks.register("showTestsSeed", {
+ doFirst {
+ logger.lifecycle("Running tests with root randomization seed: tests.seed=${rootProject.ext.rootSeed}")
+ }
+})
+
+// Wire up included builds to some validation tasks.
+tasks.matching { it.name == "tidy" }.configureEach {
+ dependsOn gradle.includedBuilds*.task(":tidy")
+}
+
+tasks.matching { it.name == "check" }.configureEach {
+ dependsOn gradle.includedBuilds*.task(":check")
+}
+
+// TODO: this shouldn't be here but it's used in multiple scripts that are racy in lazy-evaluation.
+configure(project(":lucene:core")) {
+ ext {
+ mrjarJavaVersions = [24]
+ apijars = layout.projectDirectory.dir("src/generated/jdk")
+ }
+}
+
+//
+// Allow defining external tool locations, use build options so that these options are not hidden.
+//
+buildOptions.addOption("lucene.tool.python3", "External python3 executable (path or name)", "python3")
+buildOptions.addOption("lucene.tool.perl", "External perl executable (path or name)", "perl")
+buildOptions.addOption("lucene.tool.git", "External git executable (path or name)", "git")
+
+ext.externalTool = { String name ->
+ if (name in ["python3", "perl", "git"]) {
+ return buildOptions.getOption("lucene.tool." + name).asStringProvider().get()
+ }
+ throw new GradleException("External tool named '${name}' is not defined.")
+}
+
+// TODO: These utility methods should be moved somewhere else or removed.
+allprojects {
+ ext {
+ // Utility function similar to project.exec but not emitting
+ // any output unless an error code is returned from the executed command.
+ quietExec = { closure ->
+ // Resolve any properties against the provided closure.
+ resolveStrategy = Closure.DELEGATE_ONLY
+ delegate = closure.delegate
+
+ File outputFile = File.createTempFile("exec-output-", ".txt", getTemporaryDir())
+ ExecResult result
+ boolean saveIgnoreExitValue
+ ExecSpec saveExecSpec
+
+ outputFile.withOutputStream { output ->
+ // we want to capture both stdout and stderr to the same
+ // stream but gradle attempts to close these separately
+ // (it has two independent pumping threads) and it can happen
+ // that one still tries to write something when the other closed
+ // the underlying output stream.
+ def wrapped = new java.io.FilterOutputStream(output) {
+ public void close() {
+ // no-op. we close this stream manually.
+ }
+ }
+
+ result = project.exec { ExecSpec execSpec ->
+ project.configure(execSpec, closure)
+
+ saveIgnoreExitValue = execSpec.ignoreExitValue
+ saveExecSpec = execSpec
+
+ standardOutput = wrapped
+ errorOutput = wrapped
+ ignoreExitValue true
+ }
+ }
+
+ if (result.getExitValue() != 0) {
+ // Pipe the output to console. Intentionally skips any encoding conversion
+ // and pumps raw bytes.
+ logger.error(new String(outputFile.bytes))
+
+ if (!saveIgnoreExitValue) {
+ result.rethrowFailure()
+ throw new GradleException("The executed process ${saveExecSpec.executable} " +
+ "returned an odd status " +
+ "code: ${result.exitValue}, " +
+ "output at: ${outputFile} (and logged above).")
+ }
+ } else {
+ logger.info(new String(outputFile.bytes))
+ }
+
+ return result
+ }
+
+ // Convert a list of strings, tasks and task providers into resolved tasks or task providers.
+ resolveTaskRefs = { List<Object> refs ->
+ def resolved = refs.collect {
+ if (it instanceof Task) return it
+ if (it instanceof TaskProvider) return it
+ if (it instanceof String) return project.tasks.named((String) it)
+ throw new GradleException("Can't resolve task: ${it}")
+ }
+ return resolved
+ }
+
+ // Forces sequential ordering of a list of tasks (via mustRunAfter).
+ // This method should not be required in 99% of cases, consider regular dependsOn links.
+ // This method does NOT imply any ordering between dependencies of task on the input
+ // list - the execution of these may still be unordered.
+ mustRunInOrder = { List<Object> taskList ->
+ project.afterEvaluate {
+ def resolved = resolveTaskRefs(taskList)
+
+ // Enforce sequential ordering between tasks (this does NOT apply to their dependencies!)
+ for (int i = 1; i < resolved.size(); i++) {
+ resolved[i].configure {
+ logger.info("Scheduling " + resolved[i].name + " to run after " + resolved[i - 1].name)
+ mustRunAfter resolved[i - 1]
+ }
+ }
+ }
+ return taskList
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle
new file mode 100644
index 00000000000..9ed76895a6d
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle
@@ -0,0 +1,191 @@
+/*
+ * 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 'ecjLint' task to Java projects.
+
+// Check if we need to use Lucene's storage space for interim "drop" versions of ecj
+// that are ahead of the official Maven publications.
+//
+// Drop versions are at:
+// https://www.eclipse.org/downloads/download.php?r=1&file=/eclipse/downloads/drops4/S-4.36M1-202504031800/ecj-${ecjVersion}.jar
+//
+// dweiss has access to Lucene's AWS storage space (requested via Infra).
+//
+boolean useDropMirror = deps.versions.ecj.get() in ["4.36M1"]
+if (useDropMirror) {
+ repositories {
+ exclusiveContent {
+ forRepository {
+ ivy {
+ url = 'https://s3.amazonaws.com/lucene-testdata/temp-repo/ecj/'
+ patternLayout {
+ artifact "[artifact]-[revision](.[ext])"
+ m2compatible = true
+ }
+ metadataSources {
+ it.artifact()
+ }
+ }
+ }
+ filter {
+ includeGroup "org.eclipse.jdt"
+ }
+ }
+ }
+}
+
+configurations {
+ ecjDeps
+}
+
+dependencies {
+ ecjDeps deps.ecj
+}
+
+Configuration ecjConfiguration = configurations.ecjDeps
+String javadocPrefsPath = rootProject.layout.projectDirectory.file("gradle/validation/ecj-lint/ecj.javadocs.prefs").asFile.absolutePath
+
+// Create a [sourceSetName]EcjLint task for each source set
+// with a non-empty java.srcDirs. These tasks are then
+// attached to project's "ecjLint" task.
+def lintTasks = sourceSets.collect { SourceSet sourceSet ->
+ def srcDirs = sourceSet.java.sourceDirectories
+ .filter { dir -> dir.exists() }
+
+ tasks.register(sourceSet.getTaskName("ecjLint", null), JavaExec, { JavaExec task ->
+ // This dependency is on a configuration; technically it causes
+ // all dependencies to be resolved before this task executes
+ // (this includes scheduling tasks that compile the
+ // sources from other projects for example).
+ dependsOn sourceSet.compileClasspath
+ dependsOn ecjConfiguration
+
+ // The inputs are all source files from the sourceSet.
+ inputs.files sourceSet.allSource.asFileTree
+
+ // We create a task for all source sets but ignore those
+ // that don't have any Java source directories.
+ enabled = !srcDirs.isEmpty()
+
+ // Ignore MR-JAR sourceSets.
+ if (sourceSet.name ==~ /main\d+/) {
+ enabled = false
+ }
+
+ classpath = ecjConfiguration
+ mainClass = "org.eclipse.jdt.internal.compiler.batch.Main"
+
+ // DOCS: https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-using_batch_compiler.htm
+
+ // Don't emit any .class files.
+ // Hack around "-d none" still emitting package-info.class
+ // by running in a temporary directory.
+ def tmpDst = getTemporaryDir()
+ workingDir tmpDst
+
+ args += ["-d", "none"]
+
+ assert project.java.sourceCompatibility == project.java.targetCompatibility
+
+ // Compilation environment.
+ // we use -source/-target as it is significantly faster than --release
+ args += [
+ "-source",
+ project.java.sourceCompatibility
+ ]
+ args += [
+ "-target",
+ project.java.targetCompatibility
+ ]
+ args += ["-encoding", "UTF-8"]
+ args += ["-proc:none"]
+ args += ["-nowarn"]
+ args += ["-enableJavadoc"]
+ args += [
+ "-properties",
+ javadocPrefsPath
+ ]
+
+ // We depend on modular paths.
+ def modularPaths = sourceSet.modularPathsForEcj
+ dependsOn modularPaths
+
+ // Add modular dependencies and their transitive dependencies to module path.
+ task.argumentProviders.add(modularPaths.compilationArguments)
+
+ // Add classpath, if needed.
+ task.argumentProviders.add((CommandLineArgumentProvider) {
+ // Add classpath locations in a lazy provider (can't resolve the
+ // configuration at evaluation time). Filter out non-existing entries
+ // (output folders for non-existing input source dirs like resources).
+ FileCollection cpath = modularPaths.compilationClasspath.filter { p -> p.exists() }
+ if (!cpath.isEmpty()) {
+ return [
+ "-classpath",
+ cpath.join(File.pathSeparator)
+ ]
+ } else {
+ return []
+ }
+ })
+
+ // Place input files in an external file to dodge command line argument
+ // limits. We could pass a directory but ecj seems to be buggy: when it
+ // encounters a module-info.java file it no longer compiles other source files.
+ def inputsFile = file("${tmpDst}/ecj-inputs.txt")
+ task.argumentProviders.add((CommandLineArgumentProvider) {
+ return ["@" + inputsFile.absolutePath]
+ })
+
+ doFirst {
+ modularPaths.logCompilationPaths(logger)
+
+ tmpDst.mkdirs()
+
+ // escape filename accoring to ECJ's rules:
+ // https://github.com/eclipse/aspectj.eclipse.jdt.core/blob/a05312e746b9bc2b48b4b039f6e7b5e061b5b393/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java#L1533-L1537
+ // Basically surround all whitespace by quotes:
+ def escapeFileName = { String s -> s.replaceAll(/ +/, /"$0"/) }
+ inputsFile.setText(
+ srcDirs.collectMany { dir ->
+ project.fileTree(
+ dir: dir,
+ include: "**/*.java",
+ // Exclude the benchmark class with dependencies on nekohtml, which causes module-classpath conflicts and breaks ecj.
+ exclude: "**/DemoHTMLParser.java"
+ ).files
+ }
+ // Try to sort all input files; a side-effect of this should be that module-info.java
+ // is placed first on the list, which works around ECJ bug:
+ // https://bugs.eclipse.org/bugs/show_bug.cgi?id=569833
+ .sort()
+ .collect {file -> escapeFileName(file.absolutePath.toString())}.join("\n"), "UTF-8")
+ }
+ })
+}
+
+def ecjLint = tasks.register("ecjLint", {
+ description "Lint Java sources using ECJ."
+ group "Verification"
+
+ dependsOn lintTasks
+})
+
+// Attach ecjLint to check.
+tasks.named("check").configure {
+ dependsOn ecjLint
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.error-prone.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.error-prone.gradle
new file mode 100644
index 00000000000..49a4a067af6
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.error-prone.gradle
@@ -0,0 +1,631 @@
+/*
+ * 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.
+ */
+
+// Applies error-prone for additional linting.
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+Provider<Boolean> errorproneOption = buildOptions.addBooleanOption("validation.errorprone",
+ "Applies error-prone for additional source code linting.", provider { -> rootProject.ext.isCIBuild as boolean })
+
+// make sure we can apply error-prone or provide a reason why we can't.
+String skipReason = null
+if (rootProject.ext.usesAltJvm) {
+ skipReason = "won't work with alternative java toolchain"
+} else if (errorproneOption.get() == false) {
+ if (rootProject.ext.isCIBuild) {
+ throw new GradleException("Odd, errorprone linting should always be enabled on CI builds.")
+ } else {
+ skipReason = "skipped on builds not running inside CI environments, pass -Pvalidation.errorprone=true to enable"
+ }
+}
+
+if (skipReason != null) {
+ tasks.register("errorProneSkipped", {
+ doFirst {
+ logger.warn("Errorprone linting turned off (${skipReason})")
+ }
+ })
+}
+
+allprojects { prj ->
+ if (skipReason == null) {
+ plugins.withType(JavaPlugin) {
+ project.plugins.apply(deps.plugins.errorprone.get().pluginId)
+ }
+ }
+
+ prj.plugins.withType(JavaPlugin).configureEach {
+ // LUCENE-9650: Errorprone does not work when running as a plugin inside a forked Javac process.
+ // Javac running inside Gradle works, because we have additional module system opens in place.
+ if (skipReason != null) {
+ tasks.withType(JavaCompile).configureEach { task -> task.dependsOn ":errorProneSkipped" }
+
+ // Error prone plugin adds error prone to test classpath. We need to add it here too (manually) so that
+ // versions.lock is consistent with or without error prone.
+ configurations {
+ errorprone
+ }
+ dependencies {
+ errorprone deps.errorprone
+ }
+ configurations.annotationProcessor.extendsFrom(configurations.errorprone)
+ } else {
+ dependencies {
+ errorprone deps.errorprone
+ }
+
+ tasks.withType(JavaCompile).configureEach { task ->
+ // Disable errorprone on the MR-JAR tasks
+ if (task.name ==~ /compileMain\d+Java/) {
+ options.errorprone.enabled = false
+ return
+ }
+
+ // Exclude certain files (generated ones, mostly).
+ switch (project.path) {
+ case ":lucene:core":
+ options.errorprone.excludedPaths.set(".*/StandardTokenizerImpl.java")
+ break
+
+ case ":lucene:analysis:common":
+ options.errorprone.excludedPaths.set("" +
+ ".*/HTMLStripCharFilter.java|" +
+ ".*/UAX29URLEmailTokenizerImpl.java")
+ break
+
+ case ":lucene:test-framework":
+ options.errorprone.excludedPaths.set("" +
+ ".*/EmojiTokenizationTestUnicode_11_0.java|" +
+ ".*/WordBreakTestUnicode_9_0_0.java")
+ break
+
+ case ":lucene:expressions":
+ break
+
+ case ":lucene:queryparser":
+ options.errorprone.excludedPaths.set("" +
+ ".*/classic/ParseException.java|" +
+ ".*/classic/QueryParser.java|" +
+ ".*/classic/QueryParserConstants.java|" +
+ ".*/classic/QueryParserTokenManager.java|" +
+ ".*/classic/Token.java|" +
+ ".*/classic/TokenMgrError.java|" +
+ ".*/standard/parser/ParseException.java|" +
+ ".*/standard/parser/StandardSyntaxParser.java|" +
+ ".*/standard/parser/StandardSyntaxParserConstants.java|" +
+ ".*/standard/parser/StandardSyntaxParserTokenManager.java|" +
+ ".*/standard/parser/Token.java|" +
+ ".*/standard/parser/TokenMgrError.java|" +
+ ".*/surround/parser/ParseException.java|" +
+ ".*/surround/parser/QueryParser.java|" +
+ ".*/surround/parser/QueryParserConstants.java|" +
+ ".*/surround/parser/QueryParserTokenManager.java|" +
+ ".*/surround/parser/Token.java|" +
+ ".*/surround/parser/TokenMgrError.java")
+ break
+ }
+
+ task.dependsOn ":checkJdkInternalsExportedToGradle"
+
+ options.errorprone.disableWarningsInGeneratedCode = true
+ options.errorprone.errorproneArgs = [
+ '-XepDisableAllChecks',
+ // only enable specific checks
+ '-XepAllErrorsAsWarnings',
+ // warnings still fail build by default, but allows usage of -Pjavac.failOnWarnings=false
+
+ // List of enabled/disabled checks
+ // Please keep this synced with https://errorprone.info/bugpatterns when upgrading!
+ // Do *NOT* enable checks based on their name or description. Read the source code and make sure they are useful!
+ // Most error-prone checks are not useful for non-google software.
+
+ // On by Default : ERROR
+
+ // '-Xep:AddNullMarkedToPackageInfo:OFF', // we don't use jspecify
+ // '-Xep:AlwaysThrows:OFF', // we don't use google collections
+ // '-Xep:AndroidInjectionBeforeSuper:OFF', // we don't use android
+ '-Xep:ArrayEquals:ERROR',
+ '-Xep:ArrayFillIncompatibleType:ERROR',
+ '-Xep:ArrayHashCode:ERROR',
+ '-Xep:ArrayToString:ERROR',
+ // '-Xep:ArraysAsListPrimitiveArray:OFF', // we don't use guava
+ // '-Xep:AssignmentExpression:OFF', // TODO: there are problems
+ // '-Xep:AsyncCallableReturnsNull:OFF', // we don't use guava
+ // '-Xep:AsyncFunctionReturnsNull:OFF', // we don't use guava
+ // '-Xep:AutoValueBuilderDefaultsInConstructor:OFF', // we don't use autovalue
+ // '-Xep:AutoValueConstructorOrderChecker:OFF', // we don't use autovalue
+ '-Xep:BadAnnotationImplementation:ERROR',
+ '-Xep:BadShiftAmount:ERROR',
+ '-Xep:BanClassLoader:ERROR',
+ // '-Xep:BanJNDI:OFF', // implemented with forbidden APIs instead
+ // '-Xep:BoxedPrimitiveEquality:OFF', // TODO: there are problems
+ // '-Xep:BundleDeserializationCast:OFF', // we don't use android
+ '-Xep:ChainingConstructorIgnoresParameter:ERROR',
+ // '-Xep:CheckNotNullMultipleTimes:OFF', // we don't use guava
+ // '-Xep:CheckReturnValue:OFF', // we don't use these annotations
+ '-Xep:CollectionToArraySafeParameter:ERROR',
+ // '-Xep:ComparableType:OFF',
+ '-Xep:ComparingThisWithNull:ERROR',
+ '-Xep:ComparisonOutOfRange:ERROR',
+ // '-Xep:CompatibleWithAnnotationMisuse:OFF', // we don't use this annotation
+ // '-Xep:CompileTimeConstant:OFF', // we don't use this annotation
+ '-Xep:ComputeIfAbsentAmbiguousReference:ERROR',
+ '-Xep:ConditionalExpressionNumericPromotion:ERROR',
+ '-Xep:ConstantOverflow:ERROR',
+ // '-Xep:DaggerProvidesNull:OFF', // we don't use dagger
+ '-Xep:DangerousLiteralNull:ERROR',
+ '-Xep:DeadException:ERROR',
+ '-Xep:DeadThread:ERROR',
+ '-Xep:DereferenceWithNullBranch:ERROR',
+ '-Xep:DiscardedPostfixExpression:ERROR',
+ // '-Xep:DoNotCall:OFF', // we don't use this annotation
+ // '-Xep:DoNotMock:OFF', // we don't use mocking libraries
+ // '-Xep:DoubleBraceInitialization:OFF', // we don't use guava
+ '-Xep:DuplicateBranches:ERROR',
+ '-Xep:DuplicateMapKeys:ERROR',
+ // '-Xep:DurationFrom:OFF', // we don't use Duration.from()
+ // '-Xep:DurationGetTemporalUnit:OFF', // we don't use Duration.get()
+ // '-Xep:DurationTemporalUnit:OFF', // we don't use Duration.of() etc
+ // '-Xep:DurationToLongTimeUnit:OFF', // we don't use TimeUnit.convert Duration, etc
+ // '-Xep:EmptyTopLevelDeclaration:OFF', // noisy
+ '-Xep:EqualsHashCode:ERROR',
+ '-Xep:EqualsNaN:ERROR',
+ '-Xep:EqualsNull:ERROR',
+ '-Xep:EqualsReference:ERROR',
+ '-Xep:EqualsWrongThing:ERROR',
+ // '-Xep:FloggerFormatString:OFF', // we don't use flogger
+ // '-Xep:FloggerLogVarargs:OFF', // we don't use flogger
+ // '-Xep:FloggerSplitLogStatement:OFF', // we don't use flogger
+ // '-Xep:ForOverride:OFF', // we don't use this annotation
+ // '-Xep:FormatString:OFF',
+ // '-Xep:FormatStringAnnotation:OFF', // we don't use this annotation
+ // '-Xep:FromTemporalAccessor:OFF', // we don't use .from(LocalDate) etc
+ '-Xep:FunctionalInterfaceMethodChanged:ERROR',
+ // '-Xep:FuturesGetCheckedIllegalExceptionType:OFF', // we don't use guava
+ // '-Xep:FuzzyEqualsShouldNotBeUsedInEqualsMethod:OFF', // we don't use guava
+ '-Xep:GetClassOnAnnotation:ERROR',
+ '-Xep:GetClassOnClass:ERROR',
+ // '-Xep:GuardedBy:OFF', // we don't use this annotation
+ // '-Xep:GuiceAssistedInjectScoping:OFF', // we don't use guice
+ // '-Xep:GuiceAssistedParameters:OFF', // we don't use guice
+ // '-Xep:GuiceInjectOnFinalField:OFF', // we don't use guice
+ '-Xep:HashtableContains:ERROR',
+ // '-Xep:IdentityBinaryExpression:OFF',
+ '-Xep:IdentityHashMapBoxing:ERROR',
+ // '-Xep:IgnoredPureGetter:OFF', // we don't use these annotations
+ // '-Xep:Immutable:OFF', // we don't use this annotation
+ // '-Xep:ImpossibleNullComparison:OFF', // we don't use protobuf
+ '-Xep:Incomparable:ERROR',
+ // '-Xep:IncompatibleArgumentType:OFF', // we don't use this annotation
+ // '-Xep:IncompatibleModifiers:OFF', // we don't use this annotation
+ '-Xep:IndexOfChar:ERROR',
+ '-Xep:InexactVarargsConditional:ERROR',
+ // '-Xep:InfiniteRecursion:OFF',
+ // '-Xep:InjectMoreThanOneScopeAnnotationOnClass:OFF', // we don't use this annotation
+ // '-Xep:InjectOnMemberAndConstructor:OFF', // we don't use this annotation
+ // '-Xep:InlineMeValidator:OFF', // we don't use this annotation
+ // '-Xep:InstantTemporalUnit:OFF', // we don't use Instant apis with strange temporal units
+ '-Xep:IntFloatConversion:ERROR',
+ // '-Xep:IntLiteralCast:OFF', // TODO: there are problems
+ // '-Xep:InvalidJavaTimeConstant:OFF', // we don't use impacted java.time classes (Month, etc)
+ // '-Xep:InvalidPatternSyntax:OFF',
+ '-Xep:InvalidSnippet:ERROR',
+ // '-Xep:InvalidTimeZoneID:OFF', // we don't use getTimeZone with constant IDs except UTC/GMT
+ // '-Xep:InvalidZoneId:OFF', // we don't use ZoneId.of
+ '-Xep:IsInstanceIncompatibleType:ERROR',
+ '-Xep:IsInstanceOfClass:ERROR',
+ // '-Xep:IsLoggableTagLength:OFF', // we don't use android
+ // '-Xep:JUnit3TestNotRun:OFF', // we don't use junit3
+ '-Xep:JUnit4ClassAnnotationNonStatic:ERROR',
+ '-Xep:JUnit4EmptyMethods:ERROR',
+ // '-Xep:JUnit4SetUpNotRun:OFF', // LuceneTestCase takes care
+ // '-Xep:JUnit4TearDownNotRun:OFF', // LuceneTestCase takes care
+ // '-Xep:JUnit4TestNotRun:OFF', // noisy
+ '-Xep:JUnit4TestsNotRunWithinEnclosed:ERROR',
+ '-Xep:JUnitAssertSameCheck:ERROR',
+ '-Xep:JUnitParameterMethodNotFound:ERROR',
+ // '-Xep:JavaxInjectOnAbstractMethod:OFF', // we don't this annotation
+ // '-Xep:JodaToSelf:OFF', // we don't use joda-time
+ // '-Xep:LenientFormatStringValidation:OFF' // we don't use these google libraries
+ // '-Xep:LiteByteStringUtf8:OFF', // we don't use protobuf
+ // '-Xep:LocalDateTemporalAmount:OFF', // we don't use LocalDate math
+ '-Xep:LockOnBoxedPrimitive:ERROR',
+ '-Xep:LoopConditionChecker:ERROR',
+ '-Xep:LossyPrimitiveCompare:ERROR',
+ '-Xep:MathRoundIntLong:ERROR',
+ // '-Xep:MislabeledAndroidString:OFF', // we don't use android
+ '-Xep:MisleadingEmptyVarargs:ERROR',
+ '-Xep:MisleadingEscapedSpace:ERROR',
+ // '-Xep:MissingRuntimeRetention:OFF', // we don't use this annotation
+ // '-Xep:MisplacedScopeAnnotations:OFF', // we don't use this annotation
+ // '-Xep:MissingSuperCall:OFF', // we don't use this annotation
+ // '-Xep:MissingTestCall:OFF', // we don't use guava
+ // '-Xep:MisusedDayOfYear:OFF', // we don't use date patterns
+ // '-Xep:MisusedWeekYear:OFF', // we don't use date patterns
+ // '-Xep:MixedDescriptors:OFF', // we don't use protobuf
+ // '-Xep:MockIllegalThrows:OFF', // we don't use mockito
+ // '-Xep:MockitoUsage:OFF', // we don't use mockito
+ '-Xep:ModifyingCollectionWithItself:ERROR',
+ // '-Xep:MoreThanOneInjectableConstructor:OFF', // we don't use this annotation
+ // '-Xep:MustBeClosedChecker:OFF', // we don't use this annotation
+ '-Xep:NCopiesOfChar:ERROR',
+ // '-Xep:NegativeBoolean:OFF', // TODO: there are problems
+ // '-Xep:NoCanIgnoreReturnValueOnClasses:OFF', // we don't use this annotation
+ '-Xep:NonCanonicalStaticImport:ERROR',
+ // '-Xep:NonFinalCompileTimeConstant:OFF', // we don't use this annotation
+ '-Xep:NonRuntimeAnnotation:ERROR',
+ // '-Xep:NullArgumentForNonNullParameter:OFF', // we don't use this annotation
+ '-Xep:NullTernary:ERROR',
+ // '-Xep:NullableOnContainingClass:OFF', // we don't use this annotation
+ '-Xep:OptionalEquality:ERROR',
+ '-Xep:OptionalMapUnusedValue:ERROR',
+ '-Xep:OptionalOfRedundantMethod:ERROR',
+ // '-Xep:OverlappingQualifierAndScopeAnnotation:OFF', // we don't use this annotation
+ // '-Xep:OverridesJavaxInjectableMethod:OFF', // we don't use this annotation
+ '-Xep:PackageInfo:ERROR',
+ '-Xep:ParametersButNotParameterized:ERROR',
+ // '-Xep:ParcelableCreator:OFF', // we don't use android
+ // '-Xep:PeriodFrom:OFF', // we don't use Period
+ // '-Xep:PeriodGetTemporalUnit:OFF', // we don't use Period
+ // '-Xep:PeriodTimeMath:OFF', // we don't use Period
+ // '-Xep:PreconditionsInvalidPlaceholder:OFF', // we don't use guava
+ // '-Xep:PreconditionsExpensiveString:OFF', // we don't use guava
+ // '-Xep:PrivateSecurityContractProtoAccess:OFF', // we don't use protobuf
+ // '-Xep:ProtoBuilderReturnValueIgnored:OFF', // we don't use protobuf
+ // '-Xep:ProtoFieldNullComparison:OFF', // we don't use protobuf
+ // '-Xep:ProtoStringFieldReferenceEquality:OFF', // we don't use protobuf
+ // '-Xep:ProtoTruthMixedDescriptors:OFF', // we don't use protobuf
+ // '-Xep:ProtocolBufferOrdinal:OFF', // we don't use protobuf
+ // '-Xep:ProvidesMethodOutsideOfModule:OFF', // we don't use guice
+ '-Xep:RandomCast:ERROR',
+ '-Xep:RandomModInteger:ERROR',
+ // '-Xep:RectIntersectReturnValueIgnored:OFF', // we don't use android
+ // '-Xep:RequiredModifiers:OFF', // we don't use this annotation
+ // '-Xep:RestrictedApiChecker:OFF', // we don't use this annotation
+ // '-Xep:ReturnValueIgnored:OFF', // noisy
+ '-Xep:RuleNotRun:ERROR',
+ '-Xep:SelfAssertion:ERROR',
+ '-Xep:SelfAssignment:ERROR',
+ '-Xep:SelfComparison:ERROR',
+ '-Xep:SelfEquals:ERROR',
+ '-Xep:SelfSet:ERROR',
+ // '-Xep:SetUnrecognized:OFF', // we don't use protobuf
+ // '-Xep:ShouldHaveEvenArgs:OFF', // we don't use truth
+ '-Xep:SizeGreaterThanOrEqualsZero:ERROR',
+ '-Xep:StreamToString:ERROR',
+ '-Xep:StringBuilderInitWithChar:ERROR',
+ // '-Xep:StringConcatToTextBlock:OFF', // TODO: there are problems
+ '-Xep:SubstringOfZero:ERROR',
+ '-Xep:SuppressWarningsDeprecated:ERROR',
+ // '-Xep:TemporalAccessorGetChronoField:OFF', // we don't use TemporalAccessor.get
+ // '-Xep:TestParametersNotInitialized:OFF', // we don't use this annotation
+ // '-Xep:TheoryButNoTheories:OFF', // we don't use junit theory apis/runner
+ // '-Xep:ThrowIfUncheckedKnownChecked:OFF', // we don't use this annotation
+ // '-Xep:ThrowNull:OFF', // noisy (LuceneTestCase)
+ '-Xep:TimeInStaticInitializer:ERROR',
+ // '-Xep:TreeToString:OFF', // we don't use javac API
+ // '-Xep:TryFailThrowable:OFF',
+ '-Xep:TypeParameterQualifier:ERROR',
+ '-Xep:UnicodeDirectionalityCharacters:ERROR',
+ '-Xep:UnicodeInCode:ERROR',
+ '-Xep:UnnecessaryCheckNotNull:ERROR',
+ // '-Xep:UnnecessaryCopy:OFF', // we don't use google collections
+ '-Xep:UnnecessaryTypeArgument:ERROR',
+ '-Xep:UnsafeWildcard:ERROR',
+ '-Xep:UnusedAnonymousClass:ERROR',
+ '-Xep:UnusedCollectionModifiedInPlace:ERROR',
+ '-Xep:VarTypeName:ERROR',
+ // '-Xep:WrongOneof:OFF', // we don't use protobuf
+ '-Xep:XorPower:ERROR',
+ // '-Xep:ZoneIdOfZ:OFF', // we don't use ZoneId.of
+
+ // On by Default : WARNING
+
+ // '-Xep:ASTHelpersSuggestions:OFF', // we don't use ASTHelpers
+ // '-Xep:AlmostJavadoc:OFF', // noisy (e.g. commented-out code misinterpreted as javadocs)
+ // '-Xep:AlreadyChecked:OFF', // TODO: there are problems
+ // '-Xep:AmbiguousMethodReference:OFF',
+ // '-Xep:AnnotateFormatMethod:OFF', // we don't use this annotation
+ // '-Xep:ArgumentSelectionDefectChecker:OFF', // noisy
+ // '-Xep:ArrayAsKeyOfSetOrMap:OFF', // TODO: there are problems
+ // '-Xep:ArrayRecordComponent:OFF', // TODO: there are problems
+ '-Xep:AssertEqualsArgumentOrderChecker:WARN',
+ '-Xep:AssertThrowsMultipleStatements:WARN',
+ // '-Xep:AssertionFailureIgnored:OFF', // TODO: there are problems
+ // '-Xep:AssistedInjectAndInjectOnSameConstructor:OFF', // we don't use this annotation
+ '-Xep:AttemptedNegativeZero:WARN',
+ // '-Xep:AutoValueBoxedValues:OFF', // we don't use autovalue
+ // '-Xep:AutoValueFinalMethods:OFF', // we don't use autovalue
+ // '-Xep:AutoValueImmutableFields:OFF', // we don't use autovalue
+ // '-Xep:AutoValueSubclassLeaked:OFF', // we don't use autovalue
+ '-Xep:BadComparable:WARN',
+ // '-Xep:BadImport:OFF', // TODO: there are problems
+ // '-Xep:BadInstanceof:OFF', // TODO: there are problems
+ '-Xep:BareDotMetacharacter:WARN',
+ // '-Xep:BigDecimalEquals:OFF', // BigDecimal barely used, can use forbidden-apis for this
+ // '-Xep:BigDecimalLiteralDouble:OFF', // BigDecimal barely used, can use forbidden-apis for this
+ // '-Xep:BoxedPrimitiveConstructor:OFF', // we have forbiddenapis for that
+ // '-Xep:BugPatternNaming:OFF', // we don't use this annotation
+ // '-Xep:ByteBufferBackingArray:OFF',
+ // '-Xep:CacheLoaderNull:OFF', // we don't use guava
+ // '-Xep:CanonicalDuration:OFF', // barely use Duration.of (one test), just a style thing
+ // '-Xep:CatchAndPrintStackTrace:OFF', // noisy
+ // '-Xep:CatchFail:OFF', // TODO: there are problems
+ // '-Xep:ChainedAssertionLosesContext:OFF', // we don't use truth
+ // '-Xep:CharacterGetNumericValue:OFF', // noisy
+ // '-Xep:ClassCanBeStatic:OFF', // noisy
+ // '-Xep:ClassInitializationDeadlock:OFF', // TODO: there are problems
+ '-Xep:ClassNewInstance:WARN',
+ // '-Xep:CloseableProvides:OFF', // we don't use this annotation
+ '-Xep:ClosingStandardOutputStreams:WARN',
+ // '-Xep:CollectionUndefinedEquality:OFF', // TODO: there are problems
+ '-Xep:CollectorShouldNotUseState:WARN',
+ '-Xep:ComparableAndComparator:WARN',
+ '-Xep:CompareToZero:WARN',
+ // '-Xep:ComplexBooleanConstant:OFF', // TODO: there are problems
+ // '-Xep:DateChecker:OFF', // we don't use these Date setters/ctors
+ // '-Xep:DateFormatConstant:OFF', // we don't use Date setters
+ // '-Xep:DefaultCharset:OFF', // we have forbiddenapis for that
+ // '-Xep:DefaultLocale:OFF', // we have forbiddenapis for that
+ // '-Xep:DefaultPackage:OFF',
+ '-Xep:DeprecatedVariable:WARN',
+ '-Xep:DeeplyNested:WARN',
+ // '-Xep:DirectInvocationOnMock:OFF', // we don't use mocking libraries
+ // '-Xep:DistinctVarargsChecker:OFF', // we don't use google collections
+ // '-Xep:DoNotCallSuggester:OFF', // we don't use this annotation
+ // '-Xep:DoNotClaimAnnotations:OFF', // we don't use annotation processors
+ // '-Xep:DoNotMockAutoValue:OFF', // we don't use autovalue
+ // '-Xep:DoubleCheckedLocking:OFF', // TODO: there are problems
+ '-Xep:DuplicateDateFormatField:WARN',
+ '-Xep:EmptyBlockTag:WARN',
+ // '-Xep:EmptyCatch:OFF', // ECJ takes care
+ // '-Xep:EmptySetMultibindingContributions:OFF', // we don't use this annotation
+ // '-Xep:EnumOrdinal:OFF', // noisy
+ // '-Xep:EqualsGetClass:OFF', // noisy
+ // '-Xep:EqualsIncompatibleType:OFF',
+ // '-Xep:EqualsUnsafeCast:OFF', // noisy
+ '-Xep:EqualsUsingHashCode:WARN',
+ '-Xep:ErroneousBitwiseExpression:WARN',
+ '-Xep:ErroneousThreadPoolConstructorChecker:WARN',
+ // '-Xep:EscapedEntity:OFF',
+ // '-Xep:ExtendingJUnitAssert:OFF', // noisy
+ // '-Xep:ExtendsObject:OFF', // TODO: there are problems
+ // '-Xep:FallThrough:OFF', // TODO: there are problems
+ '-Xep:Finalize:WARN',
+ // catches actual finalizers that don't call super
+ // '-Xep:Finally:OFF', // TODO: there are problems
+ '-Xep:FloatCast:WARN',
+ '-Xep:FloatingPointAssertionWithinEpsilon:WARN',
+ // '-Xep:FloatingPointLiteralPrecision:OFF', // TODO: there are problems
+ // '-Xep:FloggerArgumentToString:OFF', // we don't use flogger
+ // '-Xep:FloggerStringConcatenation:OFF', // we don't use flogger
+ // '-Xep:FragmentInjection:OFF', // we don't use android
+ // '-Xep:FragmentNotInstantiable:OFF', // we don't use android
+ // '-Xep:FutureReturnValueIgnored:OFF', // TODO: there are problems
+ // '-Xep:FutureTransformAsync:OFF', // we don't use these google libraries
+ '-Xep:GetClassOnEnum:WARN',
+ // '-Xep:GuiceNestedCombine:OFF', // we don't use guice
+ // '-Xep:HidingField:OFF', // noisy
+ '-Xep:ICCProfileGetInstance:WARN',
+ // '-Xep:IdentityHashMapUsage:OFF', // noisy
+ // '-Xep:ImmutableAnnotationChecker:OFF', // we don't use this annotation
+ // '-Xep:ImmutableEnumChecker:OFF', // noisy
+ // '-Xep:InconsistentCapitalization:OFF', // TODO: there are problems
+ // '-Xep:InconsistentHashCode:OFF', // noisy
+ // '-Xep:IgnoredPureGetter:OFF', // we don't use these google libraries
+ '-Xep:IncorrectMainMethod:WARN',
+ '-Xep:IncrementInForLoopAndHeader:WARN',
+ '-Xep:InheritDoc:WARN',
+ // '-Xep:InjectOnBugCheckers:OFF', // we don't use this annotation
+ // '-Xep:InjectInvalidTargetingOnScopingAnnotation:OFF', // we don't use this annotation
+ // '-Xep:InjectOnConstructorOfAbstractClass:OFF', // we don't use this annotation
+ // '-Xep:InjectScopeAnnotationOnInterfaceOrAbstractClass:OFF', // we don't use this annotation
+ // '-Xep:InjectedConstructorAnnotations:OFF', // we don't use this annotation
+ // '-Xep:InlineFormatString:OFF', // noisy
+ // '-Xep:InlineMeInliner:OFF', // we don't use this annotation
+ // '-Xep:InlineMeSuggester:OFF', // we don't use this annotation
+ // '-Xep:InlineTrivialConstant:OFF', // stylistic
+ // '-Xep:InputStreamSlowMultibyteRead:OFF',
+ '-Xep:InstanceOfAndCastMatchWrongType:WARN',
+ // '-Xep:IntLongMath:OFF', // noisy
+ // '-Xep:InvalidBlockTag:OFF', // noisy (e.g. lucene.experimental)
+ // '-Xep:InvalidInlineTag:OFF', // TODO: there are problems
+ '-Xep:InvalidLink:WARN',
+ // '-Xep:InvalidParam:OFF', // TODO: there are problems
+ '-Xep:InvalidThrows:WARN',
+ '-Xep:InvalidThrowsLink:WARN',
+ '-Xep:IterableAndIterator:WARN',
+ // '-Xep:JUnit3FloatingPointComparisonWithoutDelta:OFF', // we don't use junit3
+ // '-Xep:JUnit4ClassUsedInJUnit3:OFF', // we don't use junit3
+ // '-Xep:JUnitAmbiguousTestClass:OFF', // we don't use junit3
+ // '-Xep:JavaDurationGetSecondsGetNano:OFF', // we don't use these Duration methods
+ // '-Xep:JavaDurationGetSecondsToToSeconds:OFF', // we don't use these Duration methods
+ // '-Xep:JavaDurationWithNanos:OFF', // we don't use these Duration methods
+ // '-Xep:JavaDurationWithSeconds:OFF', // we don't use these Duration methods
+ // '-Xep:JavaInstantGetSecondsGetNano:OFF', // we don't use these Instant methods
+ // '-Xep:JavaLangClash:OFF', // TODO: there are problems
+ // '-Xep:JavaLocalDateTimeGetNano:OFF', // we don't use LocalDateTime
+ // '-Xep:JavaLocalTimeGetNano:OFF', // we don't use LocalTime
+ // '-Xep:JavaPeriodGetDays:OFF', // we don't use Period
+ // '-Xep:JavaTimeDefaultTimeZone:OFF', // forbidden-apis checks this
+ // '-Xep:JavaUtilDate:OFF', // noisy
+ // '-Xep:JavaxInjectOnFinalField:OFF', // we don't use this annotation
+ // '-Xep:JdkObsolete:OFF', // noisy
+ // '-Xep:JodaConstructors:OFF', // we don't use joda-time
+ // '-Xep:JodaDateTimeConstants:OFF', // we don't use joda-time
+ // '-Xep:JodaDurationWithMillis:OFF', // we don't use joda-time
+ // '-Xep:JodaInstantWithMillis:OFF', // we don't use joda-time
+ // '-Xep:JodaNewPeriod:OFF', // we don't use joda-time
+ // '-Xep:JodaPlusMinusLong:OFF', // we don't use joda-time
+ // '-Xep:JodaTimeConverterManager:OFF', // we don't use joda-time
+ // '-Xep:JodaWithDurationAddedLong:OFF', // we don't use joda-time
+ '-Xep:JUnitIncompatibleType:WARN',
+ // '-Xep:LabelledBreakTarget:OFF', // stylistic
+ // '-Xep:LiteEnumValueOf:OFF', // we don't use protobuf
+ // '-Xep:LiteProtoToString:OFF', // we don't use protobuf
+ // '-Xep:LockNotBeforeTry:OFF', // TODO: there are problems
+ // '-Xep:LockOnNonEnclosingClassLiteral:OFF', // TODO: there are problems
+ '-Xep:LogicalAssignment:WARN',
+ '-Xep:LongDoubleConversion:WARN',
+ '-Xep:LongFloatConversion:WARN',
+ '-Xep:LoopOverCharArray:WARN',
+ '-Xep:MalformedInlineTag:WARN',
+ // '-Xep:MathAbsoluteNegative:OFF', // TODO: there are problems
+ // '-Xep:MemoizeConstantVisitorStateLookups:OFF', // we don't use this class
+ // '-Xep:MisformattedTestData:OFF', // stylistic
+ // '-Xep:MissingCasesInEnumSwitch:OFF', // redundant with ECJ incompleteEnumSwitch/missingEnumCaseDespiteDefault
+ // '-Xep:MissingFail:OFF', // TODO: there are problems
+ '-Xep:MissingImplementsComparable:WARN',
+ // '-Xep:MissingOverride:OFF', // ECJ takes care of this
+ // '-Xep:MissingRefasterAnnotation:OFF', // we don't use this annotation
+ // '-Xep:MissingSummary:OFF', // TODO: there are problems
+ // '-Xep:MixedMutabilityReturnType:OFF', // noisy
+ // '-Xep:MockitoDoSetup:OFF', // we don't use mocking libraries
+ // '-Xep:MockNotUsedInProduction:OFF', // we don't use mocking libraries
+ // '-Xep:ModifiedButNotUsed:OFF', // TODO: there are problems
+ '-Xep:ModifyCollectionInEnhancedForLoop:WARN',
+ '-Xep:ModifySourceCollectionInStream:WARN',
+ '-Xep:MultimapKeys:WARN',
+ // '-Xep:MultipleNullnessAnnotations:OFF', // we don't use these annotations
+ '-Xep:MultipleParallelOrSequentialCalls:WARN',
+ '-Xep:MultipleUnaryOperatorsInMethodCall:WARN',
+ // '-Xep:MutableGuiceModule:OFF', // we don't use guice
+ // '-Xep:MutablePublicArray:OFF', // TODO: there are problems
+ '-Xep:NamedLikeContextualKeyword:WARN',
+ '-Xep:NarrowCalculation:WARN',
+ // '-Xep:NarrowingCompoundAssignment:OFF', // noisy
+ '-Xep:NegativeCharLiteral:WARN',
+ '-Xep:NestedInstanceOfConditions:WARN',
+ // '-Xep:NewFileSystem:OFF', // we don't create new filesystems
+ // '-Xep:NonApiType:OFF', // noisy
+ // '-Xep:NonAtomicVolatileUpdate:OFF', // TODO: there are problems
+ // '-Xep:NonCanonicalType:OFF', // noisy
+ '-Xep:NonFinalStaticField:WARN',
+ '-Xep:NonOverridingEquals:WARN',
+ '-Xep:NotJavadoc:WARN',
+ '-Xep:NullOptional:WARN',
+ // '-Xep:NullableConstructor:OFF', // we don't use this annotation
+ '-Xep:NullableOptional:WARN',
+ // '-Xep:NullablePrimitive:OFF', // we don't use this annotation
+ // '-Xep:NullablePrimitiveArray:OFF', // we don't use this annotation
+ // '-Xep:NullableTypeParameter:OFF', // we don't use this annotation
+ // '-Xep:NullableVoid:OFF', // we don't use this annotation
+ // '-Xep:NullableWildcard:OFF', // we don't use this annotation
+ '-Xep:ObjectEqualsForPrimitives:WARN',
+ // '-Xep:ObjectToString:OFF', // TODO: there are problems
+ // '-Xep:ObjectsHashCodePrimitive:OFF', // TODO: there are problems
+ // '-Xep:OperatorPrecedence:OFF', // noisy
+ '-Xep:OptionalMapToOptional:WARN',
+ '-Xep:OptionalNotPresent:WARN',
+ '-Xep:OrphanedFormatString:WARN',
+ // '-Xep:OutlineNone:OFF', // we don't use gwt
+ '-Xep:OverrideThrowableToString:WARN',
+ '-Xep:Overrides:WARN',
+ // '-Xep:OverridesGuiceInjectableMethod:OFF', // we don't use guice
+ '-Xep:OverridingMethodInconsistentArgumentNamesChecker:WARN',
+ // '-Xep:PatternMatchingInstanceof:OFF', // there are problems and check seems not great
+ // '-Xep:ParameterName:OFF', // we don't pass parameters with comments in this way
+ // '-Xep:PreconditionsCheckNotNullRepeated:OFF', // we don't use guava
+ '-Xep:PrimitiveAtomicReference:WARN',
+ // '-Xep:ProtectedMembersInFinalClass:OFF', // we don't use protobuf
+ // '-Xep:ProtoDurationGetSecondsGetNano:OFF', // we don't use protobuf
+ // '-Xep:ProtoRedundantSet:OFF', // we don't use protobuf
+ // '-Xep:ProtoTimestampGetSecondsGetNano:OFF', // we don't use protobuf
+ // '-Xep:QualifierOrScopeOnInjectMethod:OFF', // we don't use this annotation
+ '-Xep:ReachabilityFenceUsage:WARN',
+ // '-Xep:RedundantControlFlow:OFF', // stylistic
+ // '-Xep:RedundantSetterCall:OFF', // we don't use protobuf
+ // '-Xep:ReferenceEquality:OFF', // noisy
+ '-Xep:RethrowReflectiveOperationExceptionAsLinkageError:WARN',
+ // '-Xep:ReturnAtTheEndOfVoidFunction:OFF', // stylistic
+ '-Xep:ReturnFromVoid:WARN',
+ // '-Xep:RobolectricShadowDirectlyOn:OFF', // we don't use robolectric
+ // '-Xep:RxReturnValueIgnored:OFF', // we don't use rxjava
+ // '-Xep:SameNameButDifferent:OFF', // TODO: there are problems
+ // '-Xep:SelfAlwaysReturnsThis:OFF', // we don't use self() methods, this isn't python.
+ // '-Xep:ShortCircuitBoolean:OFF', // TODO: there are problems
+ // '-Xep:StatementSwitchToExpressionSwitch:OFF', // TODO: there are problems
+ // '-Xep:StaticAssignmentInConstructor:OFF',
+ // '-Xep:StaticAssignmentOfThrowable:OFF', // noisy
+ // '-Xep:StaticGuardedByInstance:OFF',
+ // '-Xep:StaticMockMember:OFF', // we don't use mock libraries
+ // '-Xep:StreamResourceLeak:OFF', // TODO: there are problems
+ '-Xep:StreamToIterable:WARN',
+ // '-Xep:StringCaseLocaleUsage:OFF', // noisy, can use forbidden-apis for this
+ '-Xep:StringCharset:WARN',
+ '-Xep:StringFormatWithLiteral:WARN',
+ // '-Xep:StringSplitter:OFF', // noisy, can use forbidden-apis for this
+ '-Xep:SystemConsoleNull:WARN',
+ '-Xep:SunApi:WARN',
+ '-Xep:SuperCallToObjectMethod:WARN',
+ // '-Xep:SwigMemoryLeak:OFF', // we don't use swig
+ // '-Xep:SynchronizeOnNonFinalField:OFF', // noisy
+ // '-Xep:ThreadJoinLoop:OFF',
+ // '-Xep:ThreadLocalUsage:OFF', // noisy
+ // '-Xep:ThreadPriorityCheck:OFF', // noisy, forbidden APIs can do this
+ // '-Xep:ThrowIfUncheckedKnownUnchecked:OFF', // we don't use these google libraries
+ '-Xep:ThreeLetterTimeZoneID:WARN',
+ '-Xep:TimeUnitConversionChecker:WARN',
+ // '-Xep:ToStringReturnsNull:OFF', // TODO: there are problems
+ // '-Xep:TruthAssertExpected:OFF', // we don't use truth
+ // '-Xep:TruthConstantAsserts:OFF', // we don't use truth
+ // '-Xep:TruthContainsExactlyElementsInUsage:OFF', // we don't use truth
+ // '-Xep:TruthGetOrDefault:OFF', // we don't use truth
+ // '-Xep:TruthIncompatibleType:OFF', // we don't use truth
+ // '-Xep:TypeEquals:OFF', // we don't use this internal javac api
+ '-Xep:TypeNameShadowing:WARN',
+ // '-Xep:TypeParameterShadowing:OFF',
+ // '-Xep:TypeParameterUnusedInFormals:OFF',
+ '-Xep:URLEqualsHashCode:WARN',
+ // '-Xep:UndefinedEquals:OFF', // TODO: there are problems
+ // '-Xep:UnescapedEntity:OFF', // TODO: there are problems
+ // '-Xep:UnicodeEscape:OFF', // noisy
+ '-Xep:UnnecessaryAsync:WARN',
+ // '-Xep:UnnecessaryAssignment:OFF', // we don't use these annotations
+ '-Xep:UnnecessaryBreakInSwitch:WARN',
+ // '-Xep:UnnecessaryLambda:OFF', // TODO: there are problems
+ // '-Xep:UnnecessaryLongToIntConversion:OFF', // TODO: there are problems
+ // '-Xep:UnnecessaryMethodInvocationMatcher:OFF', // we don't use spring
+ '-Xep:UnnecessaryMethodReference:WARN',
+ // '-Xep:UnnecessaryParentheses:OFF', // noisy
+ '-Xep:UnnecessaryStringBuilder:WARN',
+ // '-Xep:UnnecessaryTestMethodPrefix:OFF', // stylistic
+ // '-Xep:UnqualifiedYield:OFF', // javac takes care
+ '-Xep:UnrecognisedJavadocTag:WARN',
+ // '-Xep:UnsafeFinalization:OFF', // we don't use finalizers, deprecated for removal, fails build
+ '-Xep:UnsafeReflectiveConstructionCast:WARN',
+ // '-Xep:UnsynchronizedOverridesSynchronized:OFF', // TODO: there are problems
+ // '-Xep:UnusedLabel:OFF', // TODO: there are problems
+ // '-Xep:UnusedMethod:OFF', // TODO: there are problems
+ '-Xep:UnusedNestedClass:WARN',
+ // '-Xep:UnusedTypeParameter:OFF', // TODO: there are problems
+ // '-Xep:UnusedVariable:OFF', // noisy, can use ECJ
+ // '-Xep:UseBinds:OFF', // we don't use this annotation
+ // '-Xep:UseCorrectAssertInTests:OFF', // noisy
+ '-Xep:VariableNameSameAsType:WARN',
+ '-Xep:VoidUsed:WARN',
+ // '-Xep:WaitNotInLoop:OFF', // TODO: there are problems
+ // '-Xep:WakelockReleasedDangerously:OFF', // we don't use android
+ // '-Xep:WithSignatureDiscouraged:OFF', // we aren't using this error-prone internal api
+ ]
+ }
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.forbidden-apis.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.forbidden-apis.gradle
new file mode 100644
index 00000000000..06e578ea042
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.forbidden-apis.gradle
@@ -0,0 +1,181 @@
+/*
+ * 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 configures the application of forbidden API rules
+// via https://github.com/policeman-tools/forbidden-apis
+
+project.plugins.apply(deps.plugins.forbiddenapis.get().pluginId)
+
+def forbiddenApiRules = rootProject.layout.projectDirectory.dir("gradle/validation/forbidden-apis")
+
+// This helper method appends signature files based on a set of true
+// dependencies from a given configuration.
+def dynamicSignatures = { configuration, suffix ->
+ def resolvedMods = configuration.resolvedConfiguration.resolvedArtifacts
+ .collect { a -> a.moduleVersion.id }
+ def deps = resolvedMods
+ .collect { id ->
+ [
+ "${id.group}.${id.name}.all.txt",
+ "${id.group}.${id.name}.${suffix}.txt",
+ ]
+ }
+ .flatten()
+ .sort()
+
+ deps += [
+ "defaults.all.txt",
+ "defaults.${suffix}.txt"
+ ]
+
+ deps.each { String sig ->
+ def signaturesFile = forbiddenApiRules.file(sig)
+ if (signaturesFile.asFile.exists()) {
+ logger.info("Signature file applied: ${sig}")
+ signaturesFiles += files(signaturesFile)
+ } else {
+ logger.debug("Signature file omitted (does not exist): ${sig}")
+ }
+ }
+
+ // commons-io is special: forbiddenapis has a versioned bundledSignature.
+ bundledSignatures += resolvedMods
+ .findAll { id -> id.group == 'commons-io' && id.name == 'commons-io' }
+ .collect { id -> "${id.name}-unsafe-${id.version}" as String }
+}
+
+// Configure defaults for sourceSets.main
+tasks.matching { it.name ==~ /forbiddenApisMain\d*/ }.configureEach {
+ bundledSignatures += [
+ 'jdk-unsafe',
+ 'jdk-deprecated',
+ 'jdk-non-portable',
+ 'jdk-reflection',
+ 'jdk-system-out',
+ ]
+
+ suppressAnnotations += [
+ "**.SuppressForbidden"
+ ]
+
+ doFirst dynamicSignatures.curry(configurations.compileClasspath, "lucene")
+}
+
+// Configure defaults for the MR-JAR feature sourceSets by setting java version and ignore missing classes
+// TODO:
+// - Get hold of warning messages, see https://github.com/policeman-tools/forbidden-apis/issues/207
+tasks.matching { it.name ==~ /forbiddenApisMain\d+/ }.configureEach {
+ failOnMissingClasses = false
+}
+
+// Configure defaults for sourceSets.test
+tasks.matching {
+ it.name in [
+ "forbiddenApisTest",
+ "forbiddenApisTestFixtures"
+ ]
+}.configureEach {
+ bundledSignatures += [
+ 'jdk-unsafe',
+ 'jdk-deprecated',
+ 'jdk-non-portable',
+ 'jdk-reflection',
+ ]
+
+ signaturesFiles = files(forbiddenApiRules.file("defaults.tests.txt"))
+
+ suppressAnnotations += [
+ "**.SuppressForbidden"
+ ]
+
+ if (it.name == "forbiddenApisTestFixtures") {
+ doFirst dynamicSignatures.curry(configurations.testFixturesCompileClasspath, "lucene")
+ } else {
+ doFirst dynamicSignatures.curry(configurations.testCompileClasspath, "lucene")
+ }
+}
+
+// Configure defaults for sourceSets.tools (if present).
+tasks.matching { it.name == "forbiddenApisTools" }.configureEach {
+ bundledSignatures += [
+ 'jdk-unsafe',
+ 'jdk-deprecated',
+ 'jdk-non-portable',
+ 'jdk-reflection',
+ ]
+
+ suppressAnnotations += [
+ "**.SuppressForbidden"
+ ]
+
+ doFirst dynamicSignatures.curry(configurations.toolsCompileClasspath, "lucene")
+
+ inputs.dir(forbiddenApiRules)
+}
+
+// We rely on resolved configurations to compute the relevant set of rule
+// files for forbiddenApis. Since we don't want to resolve these configurations until
+// the task is executed, we can't really use them as task inputs properly. This is a
+// chicken-and-egg problem.
+//
+// This is the simplest workaround possible: just point at all the rule files and indicate
+// them as inputs. This way if a rule is modified, checks will be reapplied.
+tasks.matching { it.name.startsWith("forbiddenApis") }.configureEach { task ->
+ task.inputs.dir(forbiddenApiRules)
+}
+
+// Disable sysout signatures for these projects.
+if (project.name in [
+ "missing-doclet",
+ "build-infra"
+ ]) {
+ forbiddenApisMain.bundledSignatures -= [
+ 'jdk-non-portable',
+ 'jdk-system-out'
+ ]
+
+ forbiddenApisMain.exclude("**/Checksum*")
+ forbiddenApisMain.suppressAnnotations += [
+ "**.*SuppressForbidden"
+ ]
+}
+
+if (project.name in ["missing-doclet"] || project.path in [
+ ":lucene:demo",
+ ":lucene:benchmark",
+ ":lucene:test-framework"
+ ]) {
+ forbiddenApisMain.bundledSignatures -= ['jdk-system-out']
+}
+
+// the test-framework module is special in that its main sources are exported for all tests.
+// include the test signature file (defaults.tests.txt) to the main sourceset.
+if (project.path in [
+ ":lucene:test-framework"
+ ]) {
+ forbiddenApisMain.signaturesFiles += files(forbiddenApiRules.file("defaults.tests.txt"))
+}
+
+// apply logging patterns for all modules except Luke.
+if (!(project.path in [":lucene:luke"])) {
+ forbiddenApisMain.signaturesFiles += files(forbiddenApiRules.file("defaults.logging.txt"))
+}
+
+// disable forbidden apis for snowball code
+if (project.path == ":lucene:analysis:common") {
+ forbiddenApisMain.exclude("org/tartarus/**")
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.gradle-versions-cleanup.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.gradle-versions-cleanup.gradle
new file mode 100644
index 00000000000..7e5d60c1c16
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.gradle-versions-cleanup.gradle
@@ -0,0 +1,57 @@
+/*
+ * 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 cleanups to gradle/libs.gradle.toml
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+project.plugins.apply(deps.plugins.versionCatalogUpdate.get().pluginId)
+
+versionCatalogUpdate {
+ sortByKey = true
+
+ versionCatalogs {
+ deps {
+ catalogFile = file("gradle/libs.versions.toml")
+ }
+ }
+}
+
+def formatDepsTask = tasks.named("versionCatalogFormatDeps")
+def updateDepsTask = tasks.named("versionCatalogUpdateDeps")
+
+tasks.named("tidy").configure {
+ it.dependsOn(formatDepsTask)
+}
+
+// correct crlf/ default encoding after version catalog formatting finishes.
+formatDepsTask.configure {
+ it.doLast {
+ ant.fixcrlf(file: it.catalogFile.get().asFile,
+ eol: "lf", fixlast: "true", encoding: "UTF-8")
+ }
+}
+
+updateDepsTask.configure {
+ it.interactive = true
+}
+
+tasks.register("updateDeps", {
+ dependsOn updateDepsTask
+})
diff --git a/gradle/validation/gradlew-scripts-tweaked.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.gradlew-scripts-customizations.gradle
similarity index 55%
rename from gradle/validation/gradlew-scripts-tweaked.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.validation.gradlew-scripts-customizations.gradle
index 556ceabfa2c..0c4d5e38a07 100644
--- a/gradle/validation/gradlew-scripts-tweaked.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.gradlew-scripts-customizations.gradle
@@ -17,27 +17,30 @@ import java.nio.charset.StandardCharsets
* limitations under the License.
*/
-// This ensures 'gradlew*' scripts contain the manual fix so that they
-// don't fork a daemon subprocess on the initial run.
+// Check if Lucene customizations to gradlew scripts are present.
-configure(rootProject) {
- task gradlewScriptsTweaked() { task ->
- def scripts = [
- file("gradlew"),
- file("gradlew.bat")
- ]
+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)
+ inputs.files(scripts)
- doFirst {
- scripts.each { file ->
- def content = new String(file.readBytes(), StandardCharsets.US_ASCII)
- if (content.indexOf("GradlePropertiesGenerator") < 0) {
- throw new GradleException("Launch script ${file} does not have a tweak to generate gradle.properties.")
- }
+ 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?")
}
}
}
+})
- check.dependsOn gradlewScriptsTweaked
+tasks.named("check").configure {
+ dependsOn gradlewScriptsTweaked
}
diff --git a/gradle/validation/jar-checks.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.jar-checks.gradle
similarity index 74%
rename from gradle/validation/jar-checks.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.validation.jar-checks.gradle
index aacb18c3eff..c949e518263 100644
--- a/gradle/validation/jar-checks.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.jar-checks.gradle
@@ -15,49 +15,59 @@
* limitations under the License.
*/
+import org.apache.commons.codec.digest.DigestUtils
+
// This adds validation of project dependencies:
// 1) license file
// 2) notice file
// 3) checksum validation/ generation.
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+// TODO: this is a complicated mess. It should be rewritten from scratch.
+
// WARNING: The tasks in this file share internal state between tasks without using files.
// Because of this all tasks here must always execute together, so they cannot define task outputs.
// TODO: Rewrite the internal state to use state files containing the ext.jarInfos and its referencedFiles
// This should be false only for debugging.
-def failOnError = true
+boolean failOnError = true
// Configure license checksum folder for top-level projects.
// (The file("licenses") inside the configure scope resolves
// relative to the current project so they're not the same).
-configure(project(":lucene")) {
- ext.licensesDir = file("licenses")
-}
+def licensesDir = rootProject.layout.projectDirectory.dir("lucene/licenses")
+
// All known license types. If 'noticeOptional' is true then
// the notice file must accompany the license.
def licenseTypes = [
- "ASL" : [name: "Apache Software License 2.0"],
- "BSD" : [name: "Berkeley Software Distribution"],
- //BSD like just means someone has taken the BSD license and put in their name, copyright, or it's a very similar license.
- "BSD_LIKE": [name: "BSD like license"],
- "CDDL" : [name: "Common Development and Distribution License", noticeOptional: true],
- "CPL" : [name: "Common Public License"],
- "EPL" : [name: "Eclipse Public License Version 1.0", noticeOptional: true],
- "MIT" : [name: "Massachusetts Institute of Tech. License", noticeOptional: true],
- "MPL" : [name: "Mozilla Public License", noticeOptional: true /* NOT SURE on the required notice */],
- "PD" : [name: "Public Domain", noticeOptional: true],
- "PDDL" : [name: "Public Domain Dedication and License", noticeOptional: true],
- "SUN" : [name: "Sun Open Source License", noticeOptional: true],
- "COMPOUND": [name: "Compound license (details in NOTICE file)."],
+ "ASL" : [name: "Apache Software License 2.0"],
+ "BSD" : [name: "Berkeley Software Distribution"],
+ //BSD like just means someone has taken the BSD license and put in their name, copyright, or it's a very similar license.
+ "BSD_LIKE": [name: "BSD like license"],
+ "CDDL" : [name: "Common Development and Distribution License", noticeOptional: true],
+ "CPL" : [name: "Common Public License"],
+ "EPL" : [name: "Eclipse Public License Version 1.0", noticeOptional: true],
+ "MIT" : [name: "Massachusetts Institute of Tech. License", noticeOptional: true],
+ "MPL" : [name: "Mozilla Public License", noticeOptional: true /* NOT SURE on the required notice */],
+ "PD" : [name: "Public Domain", noticeOptional: true],
+ "PDDL" : [name: "Public Domain Dedication and License", noticeOptional: true],
+ "SUN" : [name: "Sun Open Source License", noticeOptional: true],
+ "COMPOUND": [name: "Compound license (details in NOTICE file)."],
]
allprojects {
- task licenses() {
+ def licensesTask = tasks.register("licenses", {
group = 'Dependency validation'
description = "Apply all dependency/ license checks."
+ })
+
+ tasks.named("check").configure {
+ dependsOn(licensesTask)
}
- check.dependsOn(licenses)
}
subprojects {
@@ -73,7 +83,7 @@ subprojects {
// For Java projects, add all dependencies from the following configurations
// to jar validation
- plugins.withType(JavaPlugin) {
+ plugins.withType(JavaPlugin).configureEach {
configurations {
jarValidation {
extendsFrom runtimeClasspath
@@ -88,7 +98,7 @@ subprojects {
// project.ext.jarInfos. Each dependency has a map of attributes
// which make it easier to process it later on (name, hash, origin module,
// see the code below for details).
- task collectJarInfos() {
+ def collectJarInfos = tasks.register("collectJarInfos", {
dependsOn configurations.jarValidation
doFirst {
@@ -130,18 +140,19 @@ subprojects {
queue.add(child)
}
}
+ def digestUtils = new DigestUtils(DigestUtils.getSha1Digest())
dep.moduleArtifacts.each { resolvedArtifact ->
def file = resolvedArtifact.file
if (visited.add(file)) {
infos.add([
- name : resolvedArtifact.name,
- jarName : file.toPath().getFileName().toString(),
- path : file,
- module : resolvedArtifact.moduleVersion,
- checksum : provider { buildinfra.sha1Digest().digestAsHex(file).trim() },
- // We keep track of the files referenced by this dependency (sha, license, notice, etc.)
- // so that we can determine unused dangling files later on.
- referencedFiles: []
+ name : resolvedArtifact.name,
+ jarName : file.toPath().getFileName().toString(),
+ path : file,
+ module : resolvedArtifact.moduleVersion,
+ checksum : provider { digestUtils.digestAsHex(file).trim() },
+ // We keep track of the files referenced by this dependency (sha, license, notice, etc.)
+ // so that we can determine unused dangling files later on.
+ referencedFiles: []
])
}
}
@@ -149,20 +160,20 @@ subprojects {
}
project.ext.jarInfos = infos.sort {a, b -> "${a.module}".compareTo("${b.module}")}
- // jarInfos.each { info -> println "${info.module}" }
}
- }
+ })
// Verifies that each JAR has a corresponding checksum and that it matches actual JAR available for this dependency.
- task validateJarChecksums() {
+ tasks.register("validateJarChecksums", {
group = 'Dependency validation'
description = "Validate checksums of dependencies"
- dependsOn collectJarInfos
+
+ dependsOn "collectJarInfos"
doLast {
def errors = []
- jarInfos.each { dep ->
- def expectedChecksumFile = file("${licensesDir}/${dep.jarName}.sha1")
+ project.ext.jarInfos.each { dep ->
+ def expectedChecksumFile = licensesDir.file("${dep.jarName}.sha1").asFile
if (!expectedChecksumFile.exists()) {
errors << "Dependency checksum missing ('${dep.module}'), expected it at: ${expectedChecksumFile}"
} else {
@@ -186,26 +197,26 @@ subprojects {
}
}
}
- }
+ })
// Locate the set of license file candidates for this dependency. We
// search for [jar-or-prefix]-LICENSE-[type].txt
// where 'jar-or-prefix' can be any '-'-delimited prefix of the dependency JAR's name.
// So for 'commons-io' it can be 'commons-io-LICENSE-foo.txt' or
// 'commons-LICENSE.txt'
- tasks.register('validateJarLicenses') {
+ tasks.register("validateJarLicenses", {
group = 'Dependency validation'
description = "Validate license and notice files of dependencies"
- dependsOn collectJarInfos
+ dependsOn "collectJarInfos"
doLast {
def errors = []
- jarInfos.each { dep ->
+ project.ext.jarInfos.each { dep ->
def baseName = dep.name
def found = []
def candidates = []
while (true) {
- candidates += file("${licensesDir}/${baseName}-LICENSE-[type].txt")
+ candidates += licensesDir.file("${baseName}-LICENSE-[type].txt").asFile
found += fileTree(dir: licensesDir, include: "${baseName}-LICENSE-*.txt").files
def prefix = baseName.replaceAll(/[\-][^-]+$/, "")
if (found || prefix == baseName) {
@@ -253,26 +264,43 @@ subprojects {
}
}
}
- }
+ })
- licenses.dependsOn validateJarChecksums, validateJarLicenses
+ tasks.named("licenses").configure {
+ dependsOn "validateJarChecksums", "validateJarLicenses"
+ }
}
// Add top-project level tasks validating dangling files
// and regenerating dependency checksums.
configure(project(":lucene")) {
- def validationTasks = subprojects.collectMany { it.tasks.matching { it.name == "licenses" } }
- def jarInfoTasks = subprojects.collectMany { it.tasks.matching { it.name == "collectJarInfos" } }
+ def excludedLicenseFiles = [
+ // Used by Luke.
+ "elegant-icon-font-*",
+ // glove knn dictionary.
+ "glove-LICENSE-PDDL.txt",
+ ]
+
+ def validationTasks = subprojects.collectMany {
+ it.tasks.matching {
+ it.name == "licenses"
+ }
+ }
+ def jarInfoTasks = subprojects.collectMany {
+ it.tasks.matching {
+ it.name == "collectJarInfos"
+ }
+ }
// Update dependency checksums.
- task updateLicenses() {
+ def updateLicenses = tasks.register("updateLicenses", {
group = 'Dependency validation'
description = "Write or update checksums of dependencies. May need to run gradlew --write-locks first if changing dependency versions"
- dependsOn jarInfoTasks
+ dependsOn "jarInfoTasks"
doLast {
- licensesDir.mkdirs()
+ licensesDir.asFile.mkdirs()
// Clean any previous checksums. In theory we wouldn't have to do it --
// dangling files from any previous JARs would be reported;
@@ -280,11 +308,11 @@ configure(project(":lucene")) {
// why not.
project.delete fileTree(licensesDir, {
include "*.sha1"
- exclude checkDanglingLicenseFiles.ext.exclude
+ exclude excludedLicenseFiles
})
def updated = []
- jarInfoTasks.collectMany { task -> task.project.jarInfos }.each { dep ->
+ jarInfoTasks.collectMany { task -> task.project.ext.jarInfos }.each { dep ->
def expectedChecksumFile = file("${licensesDir}/${dep.jarName}.sha1")
def actual = dep.checksum.get()
if (expectedChecksumFile.exists()) {
@@ -300,32 +328,30 @@ configure(project(":lucene")) {
updated.sort().each { line -> logger.log(LogLevel.LIFECYCLE, line) }
}
- }
+ })
// Any validation task must run after all updates have been applied.
// We add an ordering constraint that any validation task (or its dependency subgraph)
// must run after updateLicenses
- validationTasks
- .collectMany { task -> [task, task.dependsOn]}
- .flatten()
- .each { task ->
- task.mustRunAfter updateLicenses
- }
+ configure(subprojects) {
+ tasks.matching { it.name == "licenses" }.configureEach {
+ mustRunAfter updateLicenses
+ }
+ }
// Check for dangling files in the licenses folder.
- task checkDanglingLicenseFiles() {
- dependsOn validationTasks
+ tasks.register("checkDanglingLicenseFiles", {
+ dependsOn subprojects.collect {
+ it.tasks.matching {
+ it.name == "licenses"
+ }
+ }
ext {
// Exclude files that are not a result of direct dependencies but have to be there.
// It would be probably better to move non-dependency licenses into the actual project
// where they're used and only assemble them for the distribution package.
- exclude = [
- // Used by Luke.
- "elegant-icon-font-*",
- // glove knn dictionary.
- "glove-LICENSE-PDDL.txt",
- ]
+ exclude = excludedLicenseFiles
}
doFirst {
@@ -333,7 +359,7 @@ configure(project(":lucene")) {
// Only collect for enabled tasks: https://issues.apache.org/jira/browse/LUCENE-9780
.findAll { it.enabled }
.collectMany { task ->
- task.project.jarInfos.collectMany { it.referencedFiles }
+ task.project.ext.jarInfos.collectMany { it.referencedFiles }
}
.collect { it.toString() }
@@ -350,7 +376,9 @@ configure(project(":lucene")) {
}
}
}
- }
+ })
- licenses.dependsOn checkDanglingLicenseFiles
+ tasks.named("licenses").configure {
+ dependsOn "checkDanglingLicenseFiles"
+ }
}
diff --git a/gradle/validation/dependencies.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.lockfile.gradle
similarity index 58%
rename from gradle/validation/dependencies.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.validation.lockfile.gradle
index aca1808ee74..a15cff8a2c5 100644
--- a/gradle/validation/dependencies.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.lockfile.gradle
@@ -15,9 +15,20 @@
* limitations under the License.
*/
-// Configure sanity check for conflicting dependencies across certain configurations
+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 {
- apply plugin: deps.plugins.dependencychecks.get().pluginId
+ // 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 [
@@ -39,11 +50,19 @@ allprojects {
configurationGroups {
main_dependencies {
- include mainConfigurations
+ include provider {
+ mainConfigurations.collect {
+ it.name
+ }
+ }
}
test_dependencies {
- include testConfigurations
+ include provider {
+ testConfigurations.collect {
+ it.name
+ }
+ }
}
}
}
@@ -56,46 +75,3 @@ allprojects {
}
}
}
-
-// Configure version catalog cleanups plugin.
-configure(rootProject) {
- apply plugin: deps.plugins.versionCatalogUpdate.get().pluginId
-
- versionCatalogUpdate {
- sortByKey = true
-
- versionCatalogs {
- deps {
- catalogFile = file("gradle/libs.versions.toml")
- }
- }
- }
-
- tasks.matching { it.name == "tidy" }.configureEach {
- it.dependsOn(":versionCatalogFormatDeps")
- }
-
- // correct crlf/ default encoding after version catalog formatting finishes.
- tasks.matching {
- it.path in [
- ":versionCatalogFormatDeps"
- ]
- }.configureEach {
- it.doLast {
- ant.fixcrlf(file: it.catalogFile.get().asFile,
- eol: "lf", fixlast: "true", encoding: "UTF-8")
- }
- }
-
- tasks.matching {
- it.path in [
- ":versionCatalogUpdateDeps"
- ]
- }.configureEach {
- it.interactive = true
- }
-
- tasks.register("updateDeps", {
- dependsOn ":versionCatalogUpdateDeps"
- })
-}
\ No newline at end of file
diff --git a/gradle/validation/owasp-dependency-check.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.owasp.gradle
similarity index 54%
rename from gradle/validation/owasp-dependency-check.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.validation.owasp.gradle
index 030509a6509..aa7d9022779 100644
--- a/gradle/validation/owasp-dependency-check.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.owasp.gradle
@@ -18,29 +18,47 @@
// This adds OWASP vulnerability validation of project dependencies
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
// If -Pvalidation.owasp=true is set the validation will also run as part of the check task.
+Provider<Boolean> owaspOption = buildOptions.addBooleanOption("validation.owasp",
+ "Enable OWASP vulnerability check for dependencies.", false)
+
+Provider<Integer> owaspThresholdOption = buildOptions.addIntOption("validation.owasp.threshold",
+ "Owasp validation threshold to fail the build, if exceeded.", 7)
-def resources = scriptResources(buildscript)
+Provider<String> owaspApiKey = buildOptions.addOption("validation.owasp.apikey",
+ "Owasp validation API key (https://nvd.nist.gov/developers/request-an-api-key).")
+
+if (owaspOption.get() || gradle.startParameter.taskNames.contains("owasp")) {
+ plugins.apply(deps.plugins.owasp.dependencycheck.get().pluginId)
-configure(rootProject) {
dependencyCheck {
- failBuildOnCVSS = propertyOrDefault("validation.owasp.threshold", 7) as Integer
+ failBuildOnCVSS = owaspThresholdOption.get()
formats = ['HTML', 'JSON']
skipProjects = []
skipConfigurations = ['unifiedClasspath']
- suppressionFile = file("${resources}/exclusions.xml")
+ suppressionFile = rootProject.layout.projectDirectory.file("gradle/validation/owasp/exclusions.xml")
+
+ if (owaspApiKey.isPresent()) {
+ nvd.apiKey = owaspApiKey.get()
+ }
}
- task owasp() {
+ def owaspTask = tasks.register("owasp", {
group "Verification"
description "Check project dependencies against OWASP vulnerability database."
- dependsOn dependencyCheckAggregate
- }
+ dependsOn "dependencyCheckAggregate"
+ })
// Unless explicitly enabled, do not attach owasp to check. It has a large download
// footprint and takes a significant amount of time. This should be enabled for
// nightly CI runs only, I think.
- if (propertyOrDefault("validation.owasp", false).toBoolean()) {
- check.dependsOn owasp
+ if (owaspOption.get()) {
+ tasks.named("check").configure {
+ dependsOn owaspTask
+ }
}
}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.rat-sources.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.rat-sources.gradle
new file mode 100644
index 00000000000..2fc3c935ba5
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.rat-sources.gradle
@@ -0,0 +1,254 @@
+/*
+ * 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 groovy.xml.NamespaceBuilder
+
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
+}
+
+// Configure the rat validation task and all scanned directories.
+allprojects {
+ configurations {
+ ratDeps
+ }
+
+ dependencies {
+ ratDeps deps.rat
+ }
+
+ def ratTask = tasks.register("rat", RatTask, {
+ group = 'Verification'
+ description = 'Runs Apache Rat checks.'
+
+ dependsOn configurations.ratDeps
+
+ def defaultScanFileTree = project.fileTree(projectDir, {
+ // Don't check under the project's build folder.
+ exclude project.layout.buildDirectory.asFile.get().name
+
+ // Exclude any generated stuff.
+ exclude "src/generated"
+
+ // Don't check any of the subprojects - they have their own rat tasks.
+ exclude subprojects.collect { it.projectDir.name }
+
+ // At the module scope we only check selected file patterns as folks have various .gitignore-d resources
+ // generated by IDEs, etc.
+ include "**/*.gradle"
+ include "**/*.xml"
+ include "**/*.md"
+ include "**/*.py"
+ include "**/*.sh"
+ include "**/*.bat"
+
+ // Include selected patterns from any source folders. We could make this
+ // relative to source sets but it seems to be of little value - all our source sets
+ // live under 'src' anyway.
+ include "src/**"
+ exclude "src/**/*.png"
+ exclude "src/**/*.txt"
+ exclude "src/**/*.zip"
+ exclude "src/**/*.properties"
+ exclude "src/**/*.utf8"
+
+ // Conditionally apply module-specific patterns. We do it here instead
+ // of reconfiguring each project because the provider can be made lazy
+ // and it's easier to manage this way.
+ switch (project.path) {
+ case ":":
+ include "gradlew"
+ include "gradlew.bat"
+ exclude ".gradle"
+ exclude ".idea"
+ exclude ".muse"
+ exclude ".git"
+
+ // Exclude github stuff (templates, workflows).
+ exclude ".github"
+
+ // The root project also includes patterns for the include composite
+ // projects. Include their sources in the scan.
+ include "build-tools/build-infra/src/**"
+
+ // do not let RAT attempt to scan a python venv, it gets lost and confused...
+ exclude "dev-tools/aws-jmh/build/**"
+ exclude "dev-tools/scripts/.venv/**"
+ break
+
+ case ":lucene:analysis:morfologik":
+ exclude "src/**/*.info"
+ exclude "src/**/*.input"
+ break
+
+ case ":lucene:analysis:opennlp":
+ exclude "src/**/en-test-lemmas.dict"
+ break
+
+ case ":lucene:demo":
+ exclude "src/**/knn-token-vectors"
+ break
+
+ case ":lucene:test-framework":
+ exclude "src/**/europarl.lines.txt.seek"
+ break
+
+ case ":lucene:analysis:common":
+ case ":lucene:analysis.tests":
+ exclude "src/**/*.aff"
+ exclude "src/**/*.dic"
+ exclude "src/**/*.good"
+ exclude "src/**/*.sug"
+ exclude "src/**/*.wrong"
+ exclude "src/**/charfilter/*.htm*"
+ exclude "src/**/*LuceneResourcesWikiPage.html"
+ exclude "src/**/*.rslp"
+ break
+
+ case ":lucene:build-tools:build-infra-shadow":
+ exclude "src/**/keep.me"
+ break
+
+ case ":lucene:benchmark":
+ exclude "data/"
+ break
+ }
+ })
+ inputFileTrees.add(defaultScanFileTree)
+ })
+
+ tasks.named("check").configure {
+ dependsOn ratTask
+ }
+}
+
+/**
+ * An Apache RAT adapter that validates whether files contain acceptable licenses.
+ */
+@CacheableTask
+class RatTask extends DefaultTask {
+
+ @InputFiles
+ @PathSensitive(PathSensitivity.RELATIVE)
+ @IgnoreEmptyDirectories
+ final ListProperty<ConfigurableFileTree> inputFileTrees = project.objects.listProperty(ConfigurableFileTree)
+
+ @OutputFile
+ final RegularFileProperty xmlReport = project.objects.fileProperty().convention(
+ project.layout.buildDirectory.file("rat/rat-report.xml"))
+
+ def generateReport(File reportFile) {
+ // Set up ant rat task.
+ def ratClasspath = project.configurations.ratDeps.asPath
+ ant.setLifecycleLogLevel(AntBuilder.AntMessagePriority.ERROR)
+ ant.taskdef(resource: 'org/apache/rat/anttasks/antlib.xml', classpath: ratClasspath)
+
+ // Collect all output files for debugging.
+ String inputFileList = inputFileTrees.get().collectMany { fileTree ->
+ fileTree.asList()
+ }.sort().join("\n")
+ project.file(reportFile.path.replaceAll('.xml$', '-filelist.txt')).setText(inputFileList, "UTF-8")
+
+ // Run rat via ant.
+ ant.report(format: 'xml', reportFile: reportFile, addDefaultLicenseMatchers: true) {
+ // Pass all gradle file trees to the ant task (Gradle's internal adapters are used).
+ inputFileTrees.get().each { fileTree ->
+ fileTree.addToAntBuilder(ant, 'resources', FileCollection.AntType.ResourceCollection)
+ }
+
+ // BSD 4-clause stuff (is disallowed below)
+ substringMatcher(licenseFamilyCategory: "BSD4 ", licenseFamilyName: "Original BSD License (with advertising clause)") {
+ pattern(substring: "All advertising materials")
+ }
+
+ // BSD-like stuff
+ substringMatcher(licenseFamilyCategory: "BSD ", licenseFamilyName: "Modified BSD License") {
+ // brics automaton
+ pattern(substring: "Copyright (c) 2001-2009 Anders Moeller")
+ // snowball
+ pattern(substring: "Copyright (c) 2001, Dr Martin Porter")
+ // UMASS kstem
+ pattern(substring: "THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF MASSACHUSETTS AND OTHER CONTRIBUTORS")
+ // Egothor
+ pattern(substring: "Egothor Software License version 1.00")
+ // JaSpell
+ pattern(substring: "Copyright (c) 2005 Bruno Martins")
+ // d3.js
+ pattern(substring: "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS")
+ // highlight.js
+ pattern(substring: "THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS")
+ }
+
+ // MIT-like
+ substringMatcher(licenseFamilyCategory: "MIT ", licenseFamilyName:"Modified BSD License") {
+ // ICU license
+ pattern(substring: "Permission is hereby granted, free of charge, to any person obtaining a copy")
+ // ui-grid
+ pattern(substring: " ; License: MIT")
+ }
+
+ // Apache
+ substringMatcher(licenseFamilyCategory: "AL ", licenseFamilyName: "Apache") {
+ pattern(substring: "Licensed to the Apache Software Foundation (ASF) under")
+ // this is the old - school one under some files
+ pattern(substring: 'Licensed under the Apache License, Version 2.0 (the "License")')
+ }
+
+ substringMatcher(licenseFamilyCategory: "GEN ", licenseFamilyName: "Generated") {
+ // svg files generated by gnuplot
+ pattern(substring: "Produced by GNUPLOT")
+ // snowball stemmers generated by snowball compiler
+ pattern(substring: "Generated by Snowball")
+ // parsers generated by antlr
+ pattern(substring: "ANTLR GENERATED CODE")
+ }
+
+ approvedLicense(familyName: "Apache")
+ approvedLicense(familyName: "The MIT License")
+ approvedLicense(familyName: "Modified BSD License")
+ approvedLicense(familyName: "Generated")
+ }
+ }
+
+ def printUnknownFiles(File reportFile) {
+ def ratXml = new XmlParser().parse(reportFile)
+ def errors = []
+ ratXml.resource.each { resource ->
+ if (resource.'license-approval'.@name[0] == "false") {
+ errors << "Unknown license: ${resource.@name}"
+ }
+ }
+ if (errors) {
+ throw new GradleException("Found " + errors.size() + " file(s) with errors:\n" +
+ errors.collect{ msg -> " - ${msg}" }.join("\n"))
+ }
+ }
+
+ @TaskAction
+ def execute() {
+ def origEncoding = System.getProperty("file.encoding")
+ try {
+ File reportFile = xmlReport.get().asFile
+ generateReport(reportFile)
+ printUnknownFiles(reportFile)
+ } finally {
+ if (System.getProperty("file.encoding") != origEncoding) {
+ throw new GradleException("Something is wrong: Apache RAT changed file.encoding to ${System.getProperty('file.encoding')}?")
+ }
+ }
+ }
+}
diff --git a/gradle/validation/validate-source-patterns.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.source-patterns.gradle
similarity index 82%
rename from gradle/validation/validate-source-patterns.gradle
rename to build-tools/build-infra/src/main/groovy/lucene.validation.source-patterns.gradle
index 5adeaa0e806..509e05d106a 100644
--- a/gradle/validation/validate-source-patterns.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.source-patterns.gradle
@@ -27,54 +27,46 @@ import javax.inject.Inject;
import org.gradle.internal.logging.progress.ProgressLoggerFactory
import org.gradle.internal.logging.progress.ProgressLogger
-buildscript {
- repositories {
- mavenCentral()
- }
-
- dependencies {
- classpath deps.rat
- }
+if (project != project.rootProject) {
+ throw new GradleException("Applicable to rootProject only: " + project.path)
}
-def extensions = [
- 'adoc',
- 'bat',
- 'cmd',
- 'css',
- 'g4',
- 'gradle',
- 'groovy',
- 'html',
- 'java',
- 'jflex',
- 'jj',
- 'js',
- 'json',
- 'md',
- 'mdtext',
- 'pl',
- 'policy',
- 'properties',
- 'py',
- 'sh',
- 'template',
- 'txt',
- 'vm',
- 'xml',
- 'xsl',
+List<String> extensions = [
+ 'adoc',
+ 'bat',
+ 'cmd',
+ 'css',
+ 'g4',
+ 'gradle',
+ 'groovy',
+ 'html',
+ 'java',
+ 'jflex',
+ 'jj',
+ 'js',
+ 'json',
+ 'md',
+ 'mdtext',
+ 'pl',
+ 'policy',
+ 'properties',
+ 'py',
+ 'sh',
+ 'template',
+ 'txt',
+ 'vm',
+ 'xml',
+ 'xsl',
]
// Create source validation task local to each project
allprojects {
- task validateSourcePatterns(type: ValidateSourcePatternsTask) { task ->
+ def validateSourcePatterns = tasks.register("validateSourcePatterns", ValidateSourcePatternsTask, {
group = 'Verification'
description = 'Validate Source Patterns'
sourceFiles = fileTree(projectDir) {
- extensions.each{
- include "**/*.${it}"
- }
+ include extensions.collect { ext ->"**/*." + ext }
// Don't go into child projects (scanned separately).
childProjects.keySet().each{
@@ -85,19 +77,15 @@ allprojects {
exclude '**/build/**'
exclude '**/.idea/**'
exclude '**/.gradle/**'
-
- if (project == rootProject) {
- // ourselves :-)
- exclude 'gradle/validation/validate-source-patterns.gradle'
- } else {
- // ignore txt files in source resources and tests.
- exclude 'src/**/*.txt'
- }
+ // ignore txt files in source resources and tests.
+ exclude 'src/**/*.txt'
}
- }
+ })
// Add source validation to per-project checks as well.
- check.dependsOn validateSourcePatterns
+ 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.
@@ -106,16 +94,17 @@ allprojects {
}
}
-configure(project(':lucene:benchmark')) {
- project.tasks.withType(ValidateSourcePatternsTask) {
- sourceFiles.exclude 'data/**'
- sourceFiles.exclude 'work/**'
-
- // Known .txt offenders.
- sourceFiles.exclude '**/reuters.first20.lines.txt', '**/trecQRels.txt'
- }
+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 {
@@ -203,7 +192,7 @@ class ValidateSourcePatternsTask extends DefaultTask {
progress.start(this.name, this.name)
def validatingDecoder = StandardCharsets.UTF_8.newDecoder()
- .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)
+ .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)
sourceFiles.each { f ->
try {
@@ -213,8 +202,8 @@ class ValidateSourcePatternsTask extends DefaultTask {
String text
try {
validatingDecoder.reset()
- text = f.withInputStream {
- in -> new InputStreamReader(in, validatingDecoder).getText()
+ text = f.withInputStream { input ->
+ new InputStreamReader(input, validatingDecoder).getText()
}
} catch (CharacterCodingException e) {
reportViolation(f, "incorrect UTF-8 encoding [${e}]")
@@ -232,7 +221,7 @@ class ValidateSourcePatternsTask extends DefaultTask {
while (javadocsMatcher.find()) {
if (isLicense(javadocsMatcher, ratDocument)) {
reportViolation(f, String.format(Locale.ENGLISH, 'javadoc-style license header [%s]',
- ratDocument.getMetaData().value(MetaData.RAT_URL_LICENSE_FAMILY_NAME)));
+ ratDocument.getMetaData().value(MetaData.RAT_URL_LICENSE_FAMILY_NAME)));
}
}
if (f.name.endsWith('.java')) {
@@ -240,8 +229,8 @@ class ValidateSourcePatternsTask extends DefaultTask {
if (!f.name.contains("Test") && !f.name.contains("Mock") && !f.name.contains("Fake") && !text.contains("abstract class") &&
!f.name.equals("TokenizerFactory.java") && !f.name.equals("CharFilterFactory.java") && !f.name.equals("TokenFilterFactory.java") &&
(f.name.contains("TokenizerFactory") && text.contains("extends TokenizerFactory") ||
- f.name.contains("CharFilterFactory") && text.contains("extends CharFilterFactory") ||
- f.name.contains("FilterFactory") && text.contains("extends TokenFilterFactory"))) {
+ f.name.contains("CharFilterFactory") && text.contains("extends CharFilterFactory") ||
+ f.name.contains("FilterFactory") && text.contains("extends TokenFilterFactory"))) {
if (!validSPINameJavadocTag.matcher(text).find()) {
reportViolation(f, 'invalid spi name documentation')
}
@@ -268,8 +257,8 @@ class ValidateSourcePatternsTask extends DefaultTask {
if (!violations.isEmpty()) {
throw new GradleException(String.format(Locale.ENGLISH, 'Found %d source violation(s):\n %s',
- violations.size(),
- violations.join('\n ')))
+ 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.gradle
new file mode 100644
index 00000000000..664650dfb1c
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-groovy.gradle
@@ -0,0 +1,56 @@
+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)
+
+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:spotlessJava"
+ mustRunAfter ":lucene:build-tools:missing-doclet:renderJavadoc"
+ mustRunAfter ":lucene:build-tools:build-infra-shadow:spotlessJava"
+ mustRunAfter ":lucene:build-tools:build-infra-shadow:pluginUnderTestMetadata"
+ mustRunAfter ":lucene:build-tools:build-infra-shadow:pluginDescriptors"
+}
+
+tasks.named("tidy").configure {
+ dependsOn ":spotlessGradleScriptsApply"
+}
+
+tasks.named("check").configure {
+ dependsOn ":spotlessGradleScriptsCheck"
+}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle
new file mode 100644
index 00000000000..840e54085e7
--- /dev/null
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle
@@ -0,0 +1,108 @@
+import com.diffplug.gradle.spotless.SpotlessPlugin
+import com.diffplug.spotless.LineEnding
+
+/*
+ * 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-9564: This adds automatic (and enforced) code formatting using
+ * spotless and Google Java Format.
+ */
+
+configure(allprojects) { prj ->
+ plugins.apply(SpotlessPlugin)
+
+ plugins.withType(JavaPlugin).configureEach {
+ spotless {
+ java {
+ lineEndings(LineEnding.UNIX)
+ endWithNewline()
+ googleJavaFormat(deps.versions.googleJavaFormat.get())
+
+ // Apply to all Java sources
+ target("src/**/*.java")
+
+ // Exclude certain files (generated ones, mostly).
+ switch (prj.path) {
+ case ":lucene:build-tools:build-infra-shadow":
+ target = sourceSets.main.allJava.sourceDirectories
+ break
+
+ case ":lucene:core":
+ targetExclude("**/StandardTokenizerImpl.java")
+ break
+
+ case ":lucene:analysis:common":
+ targetExclude("**/HTMLStripCharFilter.java",
+ "**/UAX29URLEmailTokenizerImpl.java")
+ break
+
+ case ":lucene:test-framework":
+ targetExclude("**/EmojiTokenizationTestUnicode_11_0.java",
+ "**/WordBreakTestUnicode_9_0_0.java")
+ break
+
+ case ":lucene:expressions":
+ break
+
+ case ":lucene:queryparser":
+ targetExclude("**/classic/ParseException.java",
+ "**/classic/QueryParser.java",
+ "**/classic/QueryParserConstants.java",
+ "**/classic/QueryParserTokenManager.java",
+ "**/classic/Token.java",
+ "**/classic/TokenMgrError.java",
+ "**/standard/parser/ParseException.java",
+ "**/standard/parser/StandardSyntaxParser.java",
+ "**/standard/parser/StandardSyntaxParserConstants.java",
+ "**/standard/parser/StandardSyntaxParserTokenManager.java",
+ "**/standard/parser/Token.java",
+ "**/standard/parser/TokenMgrError.java",
+ "**/surround/parser/ParseException.java",
+ "**/surround/parser/QueryParser.java",
+ "**/surround/parser/QueryParserConstants.java",
+ "**/surround/parser/QueryParserTokenManager.java",
+ "**/surround/parser/Token.java",
+ "**/surround/parser/TokenMgrError.java")
+ break
+ }
+ }
+ }
+
+ // Schedule the core formatting task to run after Java compilation (GH-12012)
+ spotlessJava {
+ mustRunAfter tasks.withType(JavaCompile)
+ }
+ }
+
+ // Emit a custom message about how to fix formatting errors.
+ tasks.matching { task -> task.name == "spotlessJavaCheck" }.configureEach {
+ it.runToFixMessage.set("\nIMPORTANT: run the top-level './gradlew tidy' to " +
+ "format the code automatically (see help/formatting.txt for more info).")
+ }
+
+ // Hook up spotless to tidy and check tasks.
+ tasks.named("tidy").configure { v ->
+ v.dependsOn tasks.matching { it.name == "spotlessApply" }
+ v.dependsOn ":checkJdkInternalsExportedToGradle"
+ }
+
+ tasks.named("check").configure { v ->
+ v.dependsOn tasks.matching { it.name == "spotlessCheck" }
+ v.dependsOn ":checkJdkInternalsExportedToGradle"
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ErrorReportingTestListener.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ErrorReportingTestListener.java
index be2873ced47..a58038ff710 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ErrorReportingTestListener.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ErrorReportingTestListener.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.gradle;
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionValueSource;
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsExtension;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
@@ -27,12 +29,16 @@ import java.nio.file.Path;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import org.apache.tools.ant.types.Commandline;
import org.gradle.api.internal.tasks.testing.logging.FullExceptionFormatter;
import org.gradle.api.internal.tasks.testing.logging.TestExceptionFormatter;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
+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.TestOutputEvent;
@@ -153,6 +159,34 @@ public class ErrorReportingTestListener implements TestOutputListener, TestListe
return SANITIZE.matcher("OUTPUT-" + suite.getName() + ".txt").replaceAll("_");
}
+ // -Dtests.seed=E2469ED1547BF96C -Dtests.multiplier=3 -Dtests.directory=MMapDirectory
+ // -Dtests.locale=tok-001 -Dtests.timezone=Asia/Kuching -Dtests.asserts=true
+ // -Dtests.file.encoding=UTF-8
+ public static String getReproLineOptions(Test testTask) {
+ var buildOptions = testTask.getProject().getExtensions().getByType(BuildOptionsExtension.class);
+ var internalOptions = Set.of("tests.workDir", "tests.tmpDir");
+
+ return buildOptions.getAllOptions().stream()
+ .filter(
+ option -> {
+ return !internalOptions.contains(option.getName());
+ })
+ .filter(
+ option -> {
+ // we only care about options that have non-default values or options
+ // where values are computed are runtime (possibly randomized).
+ return option.isPresent()
+ && (option.getSource() == BuildOptionValueSource.COMPUTED_VALUE
+ || !option.isEqualToDefaultValue());
+ })
+ .map(
+ option -> {
+ return Commandline.quoteArgument(
+ "-P" + option.getName() + "=" + option.asStringProvider().get());
+ })
+ .collect(Collectors.joining(" "));
+ }
+
@Override
public void afterTest(TestDescriptor testDescriptor, TestResult result) {
// Include test failure exception stacktrace(s) in test output log.
@@ -169,7 +203,7 @@ public class ErrorReportingTestListener implements TestOutputListener, TestListe
if (!descriptor.isComposite()) {
descriptor = descriptor.getParent();
}
- return outputHandlers.computeIfAbsent(TestKey.of(descriptor), (key) -> new OutputHandler());
+ return outputHandlers.computeIfAbsent(TestKey.of(descriptor), (_) -> new OutputHandler());
}
public static class TestKey {
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/ProfileResults.java
index b5ab5abde64..5507150234b 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/ProfileResults.java
@@ -187,14 +187,14 @@ public class ProfileResults {
if (trace != null) {
StringBuilder stack = new StringBuilder();
for (int i = 0; i < Math.min(stacksize, trace.getFrames().size()); i++) {
- if (stack.length() > 0) {
+ if (!stack.isEmpty()) {
stack.append("\n").append(framePadding).append(" at ");
}
stack.append(frameToString(trace.getFrames().get(i), lineNumbers, frameTypes));
}
String line = stack.toString();
SimpleEntry<String, Long> entry =
- histogram.computeIfAbsent(line, u -> new SimpleEntry<String, Long>(line, 0L));
+ histogram.computeIfAbsent(line, _ -> new SimpleEntry<>(line, 0L));
long value = getValue(event);
entry.setValue(entry.getValue() + value);
totalEvents++;
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/buildinfra/BuildInfraPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/buildinfra/BuildInfraPlugin.java
deleted file mode 100644
index 58974090ea1..00000000000
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/buildinfra/BuildInfraPlugin.java
+++ /dev/null
@@ -1,59 +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.
- */
-package org.apache.lucene.gradle.buildinfra;
-
-import java.nio.file.Path;
-import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.lucene.gradle.Checksum;
-import org.apache.lucene.gradle.ErrorReportingTestListener;
-import org.apache.lucene.gradle.datasets.ExtractReuters;
-import org.gradle.api.Plugin;
-import org.gradle.api.Project;
-import org.gradle.api.tasks.testing.TestDescriptor;
-import org.gradle.api.tasks.testing.logging.TestLogging;
-
-public class BuildInfraPlugin implements Plugin<Project> {
- @Override
- public void apply(Project project) {
- project.getExtensions().create(BuildInfraExtension.NAME, BuildInfraExtension.class);
- }
-
- public static class BuildInfraExtension {
- public static final String NAME = "buildinfra";
-
- public ErrorReportingTestListener newErrorReportingTestListener(
- TestLogging testLogging, Path spillDir, Path outputsDir, boolean verboseMode) {
- return new ErrorReportingTestListener(testLogging, spillDir, outputsDir, verboseMode);
- }
-
- public DigestUtils sha1Digest() {
- return new DigestUtils(DigestUtils.getSha1Digest());
- }
-
- public void extractReuters(String reutersDir, String outputDir) throws Exception {
- ExtractReuters.main(new String[] {reutersDir, outputDir});
- }
-
- public String getOutputLogName(TestDescriptor suite) {
- return ErrorReportingTestListener.getOutputLogName(suite);
- }
-
- public Class<?> checksumClass() {
- return Checksum.class;
- }
- }
-}
diff --git a/build-tools/missing-doclet/build.gradle b/build-tools/missing-doclet/build.gradle
index 8036e949138..5a4f9a15ab7 100644
--- a/build-tools/missing-doclet/build.gradle
+++ b/build-tools/missing-doclet/build.gradle
@@ -15,35 +15,4 @@
* limitations under the License.
*/
-plugins {
- id 'java-library'
- alias(deps.plugins.spotless) apply false
- alias(deps.plugins.forbiddenapis) apply false
-}
-
-repositories {
- mavenCentral()
-}
-
-version = "1.0.0-SNAPSHOT"
-group = "org.apache.lucene.tools"
description = 'Doclet-based javadoc validation'
-
-// Make sure the build environment is consistent.
-apply from: file('../../gradle/conventions.gradle')
-apply from: file('../../gradle/validation/check-environment.gradle')
-
-// Add spotless/ tidy.
-tasks.register("checkJdkInternalsExportedToGradle") {}
-apply from: file('../../gradle/validation/spotless.gradle')
-apply from: file('../../gradle/validation/forbidden-apis.gradle')
-
-java {
- sourceCompatibility = JavaVersion.toVersion(deps.versions.minJava.get())
- targetCompatibility = JavaVersion.toVersion(deps.versions.minJava.get())
-}
-
-tasks.withType(JavaCompile).configureEach {
- options.compilerArgs += ["--release", java.targetCompatibility.toString()]
- options.encoding = "UTF-8"
-}
diff --git a/build-tools/missing-doclet/settings.gradle b/build-tools/missing-doclet/src/java/module-info.java
similarity index 81%
rename from build-tools/missing-doclet/settings.gradle
rename to build-tools/missing-doclet/src/java/module-info.java
index cf029b9d81f..8e5debde363 100644
--- a/build-tools/missing-doclet/settings.gradle
+++ b/build-tools/missing-doclet/src/java/module-info.java
@@ -15,10 +15,9 @@
* limitations under the License.
*/
-dependencyResolutionManagement {
- versionCatalogs {
- deps {
- from(files('../../gradle/libs.versions.toml'))
- }
- }
+/** Internal Lucene build tool (checks for missing javadocs). */
+module org.apache.lucene.missingdoclet {
+ requires java.compiler;
+ requires jdk.compiler;
+ requires jdk.javadoc;
}
diff --git a/build-tools/missing-doclet/src/main/java/org/apache/lucene/missingdoclet/MissingDoclet.java b/build-tools/missing-doclet/src/java/org/apache/lucene/missingdoclet/MissingDoclet.java
similarity index 99%
rename from build-tools/missing-doclet/src/main/java/org/apache/lucene/missingdoclet/MissingDoclet.java
rename to build-tools/missing-doclet/src/java/org/apache/lucene/missingdoclet/MissingDoclet.java
index c5d776457b6..4cd5afe195f 100644
--- a/build-tools/missing-doclet/src/main/java/org/apache/lucene/missingdoclet/MissingDoclet.java
+++ b/build-tools/missing-doclet/src/java/org/apache/lucene/missingdoclet/MissingDoclet.java
@@ -101,7 +101,7 @@ public class MissingDoclet extends StandardDoclet {
@Override
public boolean process(String option, List<String> arguments) {
- switch (arguments.get(0)) {
+ switch (arguments.getFirst()) {
case "package":
level = PACKAGE;
return true;
@@ -266,6 +266,7 @@ public class MissingDoclet extends StandardDoclet {
checkComment(element);
}
break;
+ // $CASES-OMITTED$
default:
error(element, "I don't know how to analyze " + element.getKind() + " yet.");
}
@@ -453,6 +454,7 @@ public class MissingDoclet extends StandardDoclet {
fullMessage.append(".");
fullMessage.append(element.getSimpleName());
break;
+ // $CASES-OMITTED$
default:
// for anything else, use a simple name
fullMessage.append(element.getSimpleName());
diff --git a/gradle/validation/spotless/asl-header.txt b/build-tools/missing-doclet/src/java/org/apache/lucene/missingdoclet/package-info.java
similarity index 88%
rename from gradle/validation/spotless/asl-header.txt
rename to build-tools/missing-doclet/src/java/org/apache/lucene/missingdoclet/package-info.java
index 2944f981947..77b5b46dc44 100644
--- a/gradle/validation/spotless/asl-header.txt
+++ b/build-tools/missing-doclet/src/java/org/apache/lucene/missingdoclet/package-info.java
@@ -14,3 +14,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
+/** Lucene internal build tool for detecting missing Javadocs. */
+package org.apache.lucene.missingdoclet;
diff --git a/build.gradle b/build.gradle
index 96dc4e4a7b3..ce7e5fba413 100644
--- a/build.gradle
+++ b/build.gradle
@@ -15,196 +15,72 @@
* limitations under the License.
*/
-import java.time.ZonedDateTime
-import java.time.format.DateTimeFormatter
-
plugins {
- id "base"
- id "lucene.build-infra"
-
- alias(deps.plugins.dependencychecks)
- alias(deps.plugins.spotless) apply false
- alias(deps.plugins.benmanes.versions)
- alias(deps.plugins.forbiddenapis) apply false
- alias(deps.plugins.versionCatalogUpdate) apply false
- alias(deps.plugins.randomizedtesting) apply false
- alias(deps.plugins.owasp.dependencycheck)
- alias(deps.plugins.undercouch.download) apply false
- alias(deps.plugins.errorprone) apply false
- alias(deps.plugins.jacocolog) apply false
+ // Apply convention plugins from the composite build-infra project.
+ // The order of plugins does matter (most of the time).
+ id "lucene.root-project.check-environment"
+ id "lucene.root-project.setup"
+
+ id "lucene.all-projects.conventions"
+
+ id "lucene.help"
+
+ id "lucene.java.alternative-jdk-support"
+ 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"
+ id "lucene.java.profiling"
+ id "lucene.java.beasting"
+ id "lucene.java.coverage"
+ id "lucene.java.modules"
+
+ id "lucene.validation.spotless-groovy"
+ id "lucene.validation.spotless-java"
+ 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"
+
+ 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"
+
+ id "lucene.misc.measure-task-times"
+ id "lucene.misc.pylucene"
+
+ id "lucene.datasets.external-datasets"
+
+ id "lucene.hacks.downloader-retries"
+ id "lucene.hacks.wipe-gradle-temp"
+ id "lucene.hacks.turbocharge-jvm-opts"
+ id "lucene.hacks.dummy-outputs"
+
+ id "lucene.documentation"
+ id "lucene.documentation.changes-to-html"
+ id "lucene.documentation.markdown"
+ id "lucene.documentation.render-javadoc"
+ id "lucene.documentation.check-broken-links"
+
+ id "lucene.regenerate"
+ id "lucene.regenerate.jflex"
+ id "lucene.regenerate.moman"
+ id "lucene.regenerate.kuromoji"
+ id "lucene.regenerate.nori"
+ id "lucene.regenerate.icu"
+ id "lucene.regenerate.javacc"
+ id "lucene.regenerate.antlr"
+ id "lucene.regenerate.unicode-test-classes"
+ id "lucene.regenerate.extract-jdk-apis"
}
-apply from: file('gradle/globals.gradle')
-
-// General metadata.
-
-// Calculate project version:
-version = {
- // Release manager: update base version here after release:
- String baseVersion = '11.0.0'
-
- // On a release explicitly set release version in one go:
- // -Dversion.release=x.y.z
-
- // Jenkins can just set just a suffix, overriding SNAPSHOT, e.g. using build id:
- // -Dversion.suffix=jenkins123
-
- String versionSuffix = propertyOrDefault('version.suffix', 'SNAPSHOT')
- return propertyOrDefault('version.release', "${baseVersion}-${versionSuffix}")
-}()
description = 'Grandparent project for Apache Lucene Core'
-
-// Propagate version and derived properties across projects.
-allprojects {
- version = rootProject.version
-}
-
-ext {
- // "base" version is stripped of the qualifier. Compute it.
- baseVersion = {
- def m = (version =~ /^(\d+\.\d+\.\d+)(-(.+))?/)
- if (!m) {
- throw new GradleException("Can't strip version to just x.y.z: " + rootProject.version)
- }
- return m[0][1]
- }()
- // "majorVersion" is an integer with just the major version. Compute it.
- majorVersion = {
- def m = (version =~ /^(\d+)\.\d+\.\d+(-(.+))?/)
- if (!m) {
- throw new GradleException("Can't strip version to just major version: " + rootProject.version)
- }
- return m[0][1] as int
- }
-
- // Minimum Java version required to compile and run Lucene.
- minJavaVersion = JavaVersion.toVersion(deps.versions.minJava.get())
-
- // also change this in extractor tool: ExtractForeignAPI
- vectorIncubatorJavaVersions = [
- JavaVersion.VERSION_21,
- JavaVersion.VERSION_22,
- JavaVersion.VERSION_23,
- JavaVersion.VERSION_24 ] as Set
-
- // snapshot build marker used in scripts.
- snapshotBuild = version.contains("SNAPSHOT")
-
- // Build timestamp.
- def tstamp = ZonedDateTime.now()
- buildDate = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(tstamp)
- buildTime = DateTimeFormatter.ofPattern("HH:mm:ss").format(tstamp)
- buildYear = DateTimeFormatter.ofPattern("yyyy").format(tstamp)
-
- // Allow definiting external tool locations using system props.
- externalTool = { name ->
- def resolved = propertyOrDefault("${name}.exe", name as String)
- logger.info("External tool '${name}' resolved to: ${resolved}")
- return resolved
- }
-}
-
-configurations {
- groovy
-}
-
-dependencies {
- // Use a newer groovy that doesn't have illegal reflective accesses.
- groovy deps.groovy
-}
-
-// Include smaller chunks configuring dedicated build areas.
-// Some of these intersect or add additional functionality.
-// The order of inclusion of these files shouldn't matter (but may
-// if the build file is incorrectly written and evaluates something
-// eagerly).
-apply from: file('gradle/conventions.gradle')
-apply from: file('gradle/generation/local-settings.gradle')
-
-// Make sure the build environment is consistent.
-apply from: file('gradle/validation/check-environment.gradle')
-
-// Set up defaults and configure aspects for certain modules or functionality
-// (java, tests)
-apply from: file('gradle/java/folder-layout.gradle')
-apply from: file('gradle/java/javac.gradle')
-apply from: file('gradle/java/core-mrjar.gradle')
-apply from: file('gradle/testing/defaults-tests.gradle')
-apply from: file('gradle/testing/randomization.gradle')
-apply from: file('gradle/testing/fail-on-no-tests.gradle')
-apply from: file('gradle/testing/alternative-jdk-support.gradle')
-apply from: file('gradle/java/jar-manifest.gradle')
-apply from: file('gradle/java/modules.gradle')
-
-// IDE support, settings and specials.
-apply from: file('gradle/ide/intellij-idea.gradle')
-apply from: file('gradle/ide/eclipse.gradle')
-
-// Maven artifact publishing.
-apply from: file('gradle/maven/publications.gradle')
-
-// Validation tasks
-apply from: file('gradle/validation/measure-task-times.gradle')
-apply from: file('gradle/validation/error-prone.gradle')
-apply from: file('gradle/validation/precommit.gradle')
-apply from: file('gradle/validation/forbidden-apis.gradle')
-apply from: file('gradle/validation/jar-checks.gradle')
-apply from: file('gradle/validation/git-status.gradle')
-apply from: file('gradle/validation/validate-source-patterns.gradle')
-apply from: file('gradle/validation/rat-sources.gradle')
-apply from: file('gradle/validation/owasp-dependency-check.gradle')
-apply from: file('gradle/validation/ecj-lint.gradle')
-apply from: file('gradle/validation/gradlew-scripts-tweaked.gradle')
-apply from: file('gradle/validation/dependencies.gradle')
-apply from: file('gradle/validation/spotless.gradle')
-
-// Wire up included builds to some validation tasks.
-rootProject.tasks.named("tidy").configure {
- dependsOn gradle.includedBuilds*.task(":tidy")
-}
-rootProject.tasks.named("clean").configure {
- dependsOn gradle.includedBuilds*.task(":clean")
-}
-rootProject.tasks.named("check").configure {
- dependsOn gradle.includedBuilds*.task(":forbiddenApis")
-}
-
-// Source or data regeneration tasks
-apply from: file('gradle/generation/regenerate.gradle')
-apply from: file('gradle/generation/jflex.gradle')
-apply from: file('gradle/generation/moman.gradle')
-apply from: file('gradle/generation/snowball.gradle')
-apply from: file('gradle/generation/kuromoji.gradle')
-apply from: file('gradle/generation/nori.gradle')
-apply from: file('gradle/generation/icu.gradle')
-apply from: file('gradle/generation/javacc.gradle')
-apply from: file('gradle/generation/forUtil.gradle')
-apply from: file('gradle/generation/antlr.gradle')
-apply from: file('gradle/generation/unicode-test-classes.gradle')
-apply from: file('gradle/generation/extract-jdk-apis.gradle')
-
-apply from: file('gradle/datasets/external-datasets.gradle')
-
-// Additional development aids.
-apply from: file('gradle/testing/per-project-summary.gradle')
-apply from: file('gradle/testing/slowest-tests-at-end.gradle')
-apply from: file('gradle/testing/failed-tests-at-end.gradle')
-apply from: file('gradle/testing/profiling.gradle')
-apply from: file('gradle/testing/beasting.gradle')
-apply from: file('gradle/testing/coverage.gradle')
-apply from: file('gradle/help.gradle')
-
-apply from: file('gradle/documentation/documentation.gradle')
-apply from: file('gradle/documentation/changes-to-html.gradle')
-apply from: file('gradle/documentation/markdown.gradle')
-apply from: file('gradle/documentation/render-javadoc.gradle')
-apply from: file('gradle/documentation/check-broken-links.gradle')
-
-apply from: file('gradle/hacks/downloader-retries.gradle')
-apply from: file('gradle/hacks/gradle-archives.gradle')
-apply from: file('gradle/hacks/wipe-temp.gradle')
-apply from: file('gradle/hacks/hashmapAssertions.gradle')
-apply from: file('gradle/hacks/turbocharge-jvm-opts.gradle')
-apply from: file('gradle/hacks/dummy-outputs.gradle')
-
-apply from: file('gradle/pylucene/pylucene.gradle')
diff --git a/dev-tools/scripts/buildAndPushRelease.py b/dev-tools/scripts/buildAndPushRelease.py
index f258f2b3b6b..ca27fd71786 100755
--- a/dev-tools/scripts/buildAndPushRelease.py
+++ b/dev-tools/scripts/buildAndPushRelease.py
@@ -144,7 +144,7 @@ def prepare(root: str, version: str, pause_before_sign: bool, gpg_key_id: str |
os.environ["ORG_GRADLE_PROJECT_signingPassword"] = gpg_password
else:
print(" Signing method is gpg tool")
- cmd += ' -PuseGpg -Psigning.gnupg.keyName="%s"' % gpg_key_id
+ cmd += ' -PuseGpg=true -Psigning.gnupg.keyName="%s"' % gpg_key_id
if gpg_home is not None:
cmd += ' -Psigning.gnupg.homeDir="%s"' % gpg_home
diff --git a/dev-tools/scripts/releaseWizard.yaml b/dev-tools/scripts/releaseWizard.yaml
index 01e761f26a7..d4891f25fe7 100644
--- a/dev-tools/scripts/releaseWizard.yaml
+++ b/dev-tools/scripts/releaseWizard.yaml
@@ -328,7 +328,7 @@ groups:
From the base branch {{ base_branch }} we'll run precommit tests.
Fix any problems that are found by pushing fixes to the branch
and then running this task again. This task will always do `git pull`
- before `{{ gradle_cmd }} precommit` so it will catch changes to your branch :)
+ before `{{ gradle_cmd }} check` so it will catch changes to your branch :)
confirm_each_command: false
commands:
- !Command
diff --git a/gradle/ge.gradle b/gradle/develocity.gradle
similarity index 100%
rename from gradle/ge.gradle
rename to gradle/develocity.gradle
diff --git a/gradle/documentation/render-javadoc/java21/package-list b/gradle/documentation/render-javadoc/java-24/element-list
similarity index 97%
rename from gradle/documentation/render-javadoc/java21/package-list
rename to gradle/documentation/render-javadoc/java-24/element-list
index 4d9e2fefef1..e0d8c862860 100644
--- a/gradle/documentation/render-javadoc/java21/package-list
+++ b/gradle/documentation/render-javadoc/java-24/element-list
@@ -2,6 +2,10 @@ module:java.base
java.io
java.lang
java.lang.annotation
+java.lang.classfile
+java.lang.classfile.attribute
+java.lang.classfile.constantpool
+java.lang.classfile.instruction
java.lang.constant
java.lang.foreign
java.lang.invoke
@@ -210,7 +214,6 @@ com.sun.source.tree
com.sun.source.util
com.sun.tools.javac
module:jdk.crypto.cryptoki
-module:jdk.crypto.ec
module:jdk.dynalink
jdk.dynalink
jdk.dynalink.beans
@@ -255,6 +258,7 @@ module:jdk.jstatd
module:jdk.localedata
module:jdk.management
com.sun.management
+jdk.management
module:jdk.management.agent
module:jdk.management.jfr
jdk.management.jfr
diff --git a/gradle/documentation/render-javadoc/junit-4.13.2/package-list b/gradle/documentation/render-javadoc/junit-4.13.2/package-list
new file mode 100644
index 00000000000..bbeddb092cf
--- /dev/null
+++ b/gradle/documentation/render-javadoc/junit-4.13.2/package-list
@@ -0,0 +1,20 @@
+org.hamcrest
+org.hamcrest.core
+org.junit
+org.junit.experimental
+org.junit.experimental.categories
+org.junit.experimental.max
+org.junit.experimental.results
+org.junit.experimental.runners
+org.junit.experimental.theories
+org.junit.experimental.theories.suppliers
+org.junit.function
+org.junit.matchers
+org.junit.rules
+org.junit.runner
+org.junit.runner.manipulation
+org.junit.runner.notification
+org.junit.runners
+org.junit.runners.model
+org.junit.runners.parameterized
+org.junit.validator
diff --git a/gradle/documentation/render-javadoc/junit/package-list b/gradle/documentation/render-javadoc/junit/package-list
deleted file mode 100644
index 0735177ae6e..00000000000
--- a/gradle/documentation/render-javadoc/junit/package-list
+++ /dev/null
@@ -1,7 +0,0 @@
-org.hamcrest.core
-org.junit
-org.junit.matchers
-org.junit.runner
-org.junit.runner.manipulation
-org.junit.runner.notification
-org.junit.runners
diff --git a/gradle/generation/local-settings.gradle b/gradle/generation/local-settings.gradle
deleted file mode 100644
index c33b84571a5..00000000000
--- a/gradle/generation/local-settings.gradle
+++ /dev/null
@@ -1,52 +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 script tries to guess sensible defaults for gradle parallelism
-// and local machine's resources and save them under 'gradle.properties'.
-
-def hasDefaults = rootProject.file("gradle.properties").exists()
-
-configure(rootProject) {
- // Add a task verifying that gradle process has access to JVM internals.
- // this is occasionally needed for certain tasks.
- task checkJdkInternalsExportedToGradle() {
- doFirst {
- def jdkCompilerModule = ModuleLayer.boot().findModule("jdk.compiler").orElseThrow()
- def gradleModule = getClass().module
- def internalsExported = [
- "com.sun.tools.javac.api",
- "com.sun.tools.javac.file",
- "com.sun.tools.javac.parser",
- "com.sun.tools.javac.tree",
- "com.sun.tools.javac.util"
- ].stream()
- .allMatch(pkg -> jdkCompilerModule.isExported(pkg, gradleModule))
-
- if (!internalsExported) {
- throw new GradleException(
- "Certain gradle tasks and plugins require access to jdk.compiler" +
- " internals, your gradle.properties might have just been generated or could be" +
- " out of sync (see gradle/template.gradle.properties)")
- }
- }
- }
-}
-
-task localSettings() {
- // This is just a placeholder until all references to the localSettings task are removed
-}
diff --git a/gradle/generation/regenerate.gradle b/gradle/generation/regenerate.gradle
deleted file mode 100644
index d23cfd7d54f..00000000000
--- a/gradle/generation/regenerate.gradle
+++ /dev/null
@@ -1,275 +0,0 @@
-import groovy.json.JsonOutput
-import groovy.json.JsonSlurper
-import java.util.function.Function
-
-/*
- * 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.
- */
-
-// Create common 'regenerate' task sub-tasks can hook into.
-
-/**
- * Compute all "checksummed" key-value pairs.
- */
-def computeChecksummedEntries = { Task sourceTask ->
- // An flat ordered map of key-value pairs.
- Map<String, String> allEntries = new TreeMap<>()
-
- // Make sure all input properties are either simple strings
- // or closures returning simple strings.
- //
- // Don't overcomplicate things with other serializable types.
- Map<String, Object> props = sourceTask.inputs.properties
- props.forEach { key, val ->
- // Handle closures and other lazy providers.
- if (val instanceof Provider<?>) {
- val = val.get()
- }
- if (val instanceof Closure<?>) {
- val = val.call()
- }
-
- if (!(val instanceof String)) {
- throw new GradleException("Input properties of wrapped tasks must all be " +
- "strings: ${key} in ${sourceTask.name} is not.")
- }
- allEntries.put("property:" + key, (String) val)
- }
-
- // Collect all of task inputs/ output files and compute their checksums.
- FileCollection allFiles = sourceTask.inputs.files + sourceTask.outputs.files
-
- // Compute checksums for root-project relative paths
- allFiles.files.forEach { file ->
- allEntries.put(
- sourceTask.project.rootDir.relativePath(file),
- file.exists() ? buildinfra.sha1Digest().digestAsHex(file).trim() : "--")
- }
-
- return allEntries
-}
-
-configure(rootProject) {
- ext {
- /**
- * Utility function to read a file, apply changes to its content and write it back.
- */
- modifyFile = { File path, Function<String, String> modify ->
- Function<String, String> normalizeEols = { text -> text.replace("\r\n", "\n") }
-
- String original = path.getText("UTF-8")
- String modified = normalizeEols.apply(original)
- modified = modify.apply(modified)
- modified = normalizeEols.apply(modified)
- if (!original.equals(modified)) {
- path.write(modified, "UTF-8")
- }
- }
- }
-}
-
-configure([
- project(":lucene:analysis:common"),
- project(":lucene:analysis:icu"),
- project(":lucene:analysis:kuromoji"),
- project(":lucene:analysis:nori"),
- project(":lucene:backward-codecs"),
- project(":lucene:core"),
- project(":lucene:queryparser"),
- project(":lucene:expressions"),
- project(":lucene:test-framework"),
-]) {
- task regenerate() {
- description "Rerun any code or static data generation tasks."
- group "generation"
- }
-
- project.ext {
- // This utility method implements the logic required for "persistent" incremental
- // source-generating tasks. The idea is simple, the implementation quite complex.
- //
- // The idea is that, given source-generating task "sourceTaskInternal" (note the suffix),
- // we create a bunch of other tasks that perform checksum generation, validation and
- // source task skipping. For example, let's say we have a task 'genFooInternal";
- // the following tasks would be created
- //
- // genFooChecksumLoad
- // genFooChecksumSave
- // genFooChecksumCheck (fails if checksums are inconsistent)
- //
- // and the following set of dependencies would be created (with additional
- // constraints to run them in this particular order!).
- //
- // genFoo.dependsOn [genFooChecksumLoad, genFooInternal, genFooChecksumSave]
- //
- // Checksums are persisted and computed from sourceTask's inputs/outputs. If the
- // persisted checksums are identical to the now-current checksums, the "internal" task
- // is skipped (using onlyIf { false }).
- //
- // Implementation-wise things get complicated because gradle doesn't have the notion
- // of "ordered" task execution with respect to task AND its dependencies (we can add
- // constraints to each node in the execution graph but not node-and-dependencies).
- //
- // sourceTask - the task to wrap
- // extraConfig - a map with extra (optional) configuration options.
- // andThenTasks: any other tasks that should be scheduled to run after the internal task and
- // before checksum calculation/ saving. spotless is a good example of this.
- // ignoreWithSource: any other tasks that should be ignored if the internal task is ignored
- // (checksums are identical)
- // mustRunBefore: any tasks which should be scheduled to run after the internal task.
- wrapWithPersistentChecksums = { Task sourceTask, Map<String, Object> extraConfig = [:] ->
- if (!sourceTask.name.endsWith("Internal")) {
- throw new GradleException("Wrapped task must follow the convention name of *Internal: ${sourceTask.name}")
- }
-
- String sourceTaskName = sourceTask.name.replaceAll('Internal$', '')
-
- def toList = { value ->
- if (value instanceof List) {
- return value
- } else if (value == null) {
- return []
- } else {
- return [ value ]
- }
- }
-
- List<Object> andThenTasks = toList(extraConfig.get("andThenTasks"))
- List<Object> ignoreWithSource = toList(extraConfig.get("ignoreWithSource"))
-
- // Schedule must-run-afters
- List<Object> mustRunBefore = toList(extraConfig.get("mustRunBefore"))
- // TODO: maybe ensure all task refs here are strings?
- tasks.matching { it.name in mustRunBefore }.configureEach {
- mustRunAfter sourceTask
- }
-
- // Create checksum-loader task.
- Task checksumLoadTask = tasks.create("${sourceTaskName}ChecksumLoad", {
- ext {
- checksumMatch = true
- }
-
- doFirst {
- // Current persisted task input/outputs (file checksums, properties)
- ext.currentChecksums = computeChecksummedEntries(sourceTask)
-
- // Load any previously written checksums
- ext.savedChecksums = new TreeMap<>()
- ext.checksumsFile = project.file("src/generated/checksums/${sourceTaskName}.json")
- if (checksumsFile.exists()) {
- savedChecksums.putAll(new JsonSlurper().parse(checksumsFile) as Map)
- }
-
- // Compare saved and current checksums for subsequent tasks.
- ext.checksumMatch = (savedChecksums.equals(currentChecksums))
- }
- })
-
- Task checksumCheckTask = tasks.create("${sourceTaskName}ChecksumCheck", {
- dependsOn checksumLoadTask
-
- doFirst {
- if (!checksumLoadTask.checksumMatch) {
- // This can be made prettier but leave it verbose for now:
- Map<String, String> current = checksumLoadTask.currentChecksums
- Map<String, String> expected = checksumLoadTask.savedChecksums
-
- def same = current.intersect(expected)
- current = current - same
- expected = expected - same
-
- throw new GradleException("Checksums mismatch for derived resources; you might have" +
- " modified a generated resource (regenerate task: ${sourceTaskName}):\n" +
- "Current:\n ${current.entrySet().join('\n ')}\n\n" +
- "Expected:\n ${expected.entrySet().join('\n ')}\n\n" +
- "Input files for this task are:\n " + sourceTask.inputs.files.join('\n ') + "\n\n" +
- "Files generated by this task are:\n " + sourceTask.outputs.files.join('\n ')
- )
- }
- }
- })
- check.dependsOn checksumCheckTask
-
- Task checksumSaveTask = tasks.create("${sourceTaskName}ChecksumSave", {
- dependsOn checksumLoadTask
-
- doFirst {
- File checksumsFile = checksumLoadTask.ext.checksumsFile
- checksumsFile.parentFile.mkdirs()
-
- // Recompute checksums after the task has completed and write them.
- def updatedChecksums = computeChecksummedEntries(sourceTask)
- checksumsFile.setText(
- JsonOutput.prettyPrint(JsonOutput.toJson(new TreeMap<String, String>(updatedChecksums))), "UTF-8")
-
- logger.warn("Updated generated file checksums for task ${sourceTask.path}.")
- }
- })
-
- Task conditionalTask = tasks.create("${sourceTaskName}", {
- def deps = [
- checksumLoadTask,
- sourceTask,
- *andThenTasks,
- checksumSaveTask
- ].flatten()
-
- dependsOn deps
- mustRunInOrder deps
-
- doFirst {
- if (checksumLoadTask.checksumMatch && !sourceTask.didWork) {
- logger.lifecycle("Checksums consistent with sources, skipping task: ${sourceTask.path}")
- }
- }
- })
-
- // Load checksums before the source task executes, otherwise it's always ignored.
- project.afterEvaluate {
- resolveTaskRefs([sourceTask, *ignoreWithSource]).each { t ->
- t.configure {
- dependsOn checksumLoadTask
- }
- }
- }
-
- // Copy the description and group from the source task.
- project.afterEvaluate {
- conditionalTask.group sourceTask.group
- conditionalTask.description sourceTask.description + " (if sources changed)"
-
- // Hide low-level tasks from help.
- sourceTask.group = null
- sourceTask.description sourceTask.description + " (low-level)"
- }
-
- // Set conditional execution only if checksum mismatch occurred.
- if (!gradle.startParameter.isRerunTasks()) {
- project.afterEvaluate {
- resolveTaskRefs([sourceTask, *ignoreWithSource, checksumSaveTask]).each { t ->
- t.configure {
- logger.info("Making " + t.name + " run only if " + checksumLoadTask.name + " indicates changes")
- onlyIf { !checksumLoadTask.checksumMatch }
- }
- }
- }
- }
-
- return conditionalTask
- }
- }
-}
diff --git a/gradle/globals.gradle b/gradle/globals.gradle
deleted file mode 100644
index bcab6461ea9..00000000000
--- a/gradle/globals.gradle
+++ /dev/null
@@ -1,152 +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.
- */
-
-allprojects {
- apply plugin: 'base'
-
- group "org.apache"
-
- // Repositories to fetch dependencies from.
- repositories {
- mavenCentral()
- }
-
- // Artifacts will have names after full gradle project path
- // so :solr:core will have solr-core.jar, etc.
- project.base.archivesName = project.path.replaceAll("^:", "").replace(':', '-')
-
- ext {
- // Utility method to support passing overrides via -P or -D.
- propertyOrDefault = { propName, defValue ->
- def result
- if (project.hasProperty(propName)) {
- result = project.getProperty(propName)
- } else if (System.properties.containsKey(propName)) {
- result = System.properties.get(propName)
- } else if (defValue instanceof Closure) {
- result = defValue.call()
- } else {
- result = defValue
- }
- return result
- }
-
- // System environment variable or default.
- envOrDefault = { envName, defValue ->
- def result = System.getenv(envName)
- if (result == null) {
- result = defValue
- }
- return result
- }
-
- // Either a project, system property, environment variable or default value.
- propertyOrEnvOrDefault = { propName, envName, defValue ->
- return propertyOrDefault(propName, envOrDefault(envName, defValue));
- }
-
- // Utility function similar to project.exec but not emitting
- // any output unless an error code is returned from the executed command.
- quietExec = { closure ->
- // Resolve any properties against the provided closure.
- resolveStrategy = Closure.DELEGATE_ONLY
- delegate = closure.delegate
-
- File outputFile = File.createTempFile("exec-output-", ".txt", getTemporaryDir())
- ExecResult result
- boolean saveIgnoreExitValue
- ExecSpec saveExecSpec
-
- outputFile.withOutputStream { output ->
- // we want to capture both stdout and stderr to the same
- // stream but gradle attempts to close these separately
- // (it has two independent pumping threads) and it can happen
- // that one still tries to write something when the other closed
- // the underlying output stream.
- def wrapped = new java.io.FilterOutputStream(output) {
- public void close() {
- // no-op. we close this stream manually.
- }
- }
-
- result = project.exec { ExecSpec execSpec ->
- project.configure(execSpec, closure)
-
- saveIgnoreExitValue = execSpec.ignoreExitValue
- saveExecSpec = execSpec
-
- standardOutput = wrapped
- errorOutput = wrapped
- ignoreExitValue true
- }
- }
-
- if (result.getExitValue() != 0) {
- // Pipe the output to console. Intentionally skips any encoding conversion
- // and pumps raw bytes.
- logger.error(new String(outputFile.bytes))
-
- if (!saveIgnoreExitValue) {
- result.rethrowFailure()
- throw new GradleException("The executed process ${saveExecSpec.executable} " +
- "returned an odd status " +
- "code: ${result.exitValue}, " +
- "output at: ${outputFile} (and logged above).")
- }
- } else {
- logger.info(new String(outputFile.bytes))
- }
-
- return result
- }
-
- // Convert a list of strings, tasks and task providers into resolved tasks or task providers.
- resolveTaskRefs = { List<Object> refs ->
- def resolved = refs.collect {
- if (it instanceof Task) return it
- if (it instanceof TaskProvider) return it
- if (it instanceof String) return project.tasks.named((String) it)
- throw new GradleException("Can't resolve task: ${it}")
- }
- return resolved
- }
-
- // Forces sequential ordering of a list of tasks (via mustRunAfter).
- // This method should not be required in 99% of cases, consider regular dependsOn links.
- // This method does NOT imply any ordering between dependencies of task on the input
- // list - the execution of these may still be unordered.
- mustRunInOrder = { List<Object> taskList ->
- project.afterEvaluate {
- def resolved = resolveTaskRefs(taskList)
-
- // Enforce sequential ordering between tasks (this does NOT apply to their dependencies!)
- for (int i = 1; i < resolved.size(); i++) {
- resolved[i].configure {
- logger.info("Scheduling " + resolved[i].name + " to run after " + resolved[i - 1].name)
- mustRunAfter resolved[i - 1]
- }
- }
- }
- return taskList
- }
-
- // detect if we run in CI environment by looking at existence of env vars:
- // "CI": Github (https://docs.github.com/en/actions/learn-github-actions/environment-variables)
- // anything starting with "JENKINS_" or "HUDSON_": Jenkins/Hudson (https://jenkins.thetaphi.de/env-vars.html/)
- isCIBuild = System.getenv().keySet().find { it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/ } != null
- }
-}
diff --git a/gradle/hacks/hashmapAssertions.gradle b/gradle/hacks/hashmapAssertions.gradle
deleted file mode 100644
index 095726c9701..00000000000
--- a/gradle/hacks/hashmapAssertions.gradle
+++ /dev/null
@@ -1,33 +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.
- */
-
-// Disable assertions for HashMap due to: LUCENE-8991 / JDK-8205399
-def vmName = System.getProperty("java.vm.name")
-def spec = System.getProperty("java.specification.version")
-if (vmName =~ /(?i)(hotspot|openjdk|jrockit)/ &&
- spec =~ /^(1\.8|9|10|11)$/ &&
- !Boolean.parseBoolean(propertyOrDefault('tests.asserts.hashmap', 'false'))) {
- logger.info("Enabling HashMap assertions.")
- allprojects {
- plugins.withType(JavaPlugin) {
- tasks.withType(Test) { task ->
- jvmArgs("-da:java.util.HashMap")
- }
- }
- }
-}
-
diff --git a/gradle/hacks/turbocharge-jvm-opts.gradle b/gradle/hacks/turbocharge-jvm-opts.gradle
deleted file mode 100644
index e730d878080..00000000000
--- a/gradle/hacks/turbocharge-jvm-opts.gradle
+++ /dev/null
@@ -1,69 +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"] }.all {
- 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) { 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) { 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/gradle/hacks/wipe-temp.gradle b/gradle/hacks/wipe-temp.gradle
deleted file mode 100644
index 1ae2e502ac5..00000000000
--- a/gradle/hacks/wipe-temp.gradle
+++ /dev/null
@@ -1,76 +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.file.Files
-import java.time.temporal.ChronoUnit
-import java.time.Instant
-
-
-// See LUCENE-9471. We redirect temporary location for gradle
-// so that it doesn't pollute user's tmp. Wipe it during a clean though.
-configure(rootProject) {
- gradle.buildFinished {
- // we clean up the java.io.tmpdir we've redirected gradle to use (LUCENE-9471).
- // these are still used and populated with junk.
- rootProject.delete fileTree(".gradle/tmp").matching {
- include "gradle-worker-classpath*"
- }
-
- // clean up any files older than 3 hours from the user's gradle temp. the time
- // limit is added so that we don't interfere with any concurrent builds... just in case.
- Instant deadline = Instant.now().minus(3, ChronoUnit.HOURS);
- def toDelete = new ArrayList<>()
-
- def gradleTmp = gradle.gradleUserHomeDir.toPath().resolve(".tmp")
- if (Files.exists(gradleTmp)) {
- toDelete.add(Files.list(gradleTmp))
- }
- def daemonDir = gradle.gradleUserHomeDir.toPath().resolve("daemon").resolve("${gradle.gradleVersion}")
- if (Files.exists(daemonDir)) {
- toDelete.add(Files.list(daemonDir).filter(path -> path.toString().endsWith(".out.log")))
- }
-
- try (def stream = toDelete.stream().flatMap(p -> p)) {
- stream.filter(p -> Files.isRegularFile(p))
- .filter(p -> Files.getLastModifiedTime(p).toInstant().isBefore(deadline))
- .forEach(p -> {
- Files.deleteIfExists(p)
- })
- }
- }
-}
-
-// Make sure we clean up after running tests.
-allprojects {
- plugins.withType(JavaPlugin) {
- def temps = []
-
- task wipeTaskTemp() {
- doLast {
- temps.each { temp ->
- project.delete fileTree(temp).matching {
- include "jar_extract*"
- }
- }
- }
- }
-
- tasks.withType(Test) {
- finalizedBy wipeTaskTemp
- temps += temporaryDir
- }
- }
-}
diff --git a/gradle/help.gradle b/gradle/help.gradle
deleted file mode 100644
index 620a09ff37c..00000000000
--- a/gradle/help.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.
- */
-
-// Add "help" tasks which display plain text files under 'help' folder.
-
-configure(rootProject) {
- def helpFiles = [
- ["Workflow", "help/workflow.txt", "Typical workflow commands."],
- ["Tests", "help/tests.txt", "Tests, filtering, beasting, etc."],
- ["Formatting", "help/formatting.txt", "Code formatting conventions."],
- ["Jvms", "help/jvms.txt", "Using alternative or EA JVM toolchains."],
- ["Deps", "help/dependencies.txt", "Declaring, inspecting and excluding dependencies."],
- ["ForbiddenApis", "help/forbiddenApis.txt", "How to add/apply rules for forbidden APIs."],
- ["LocalSettings", "help/localSettings.txt", "Local settings, overrides and build performance tweaks."],
- ["Regeneration", "help/regeneration.txt", "How to refresh generated and derived resources."],
- ["Jmh", "help/jmh.txt", "JMH micro-benchmarks."],
- ["Git", "help/git.txt", "Git assistance and guides."],
- ["IDEs", "help/IDEs.txt", "IDE support."],
- ["Publishing", "help/publishing.txt", "Maven and other artifact publishing, signing, etc."],
- ]
-
- helpFiles.each { section, path, sectionInfo ->
- task "help${section}" {
- group = 'Help (developer guides and hints)'
- description = sectionInfo
- doFirst {
- println "\n" + rootProject.file(path).getText("UTF-8")
- }
- }
- }
-
- help {
- doLast {
- println ""
- println "This is Lucene's gradle build. See some"
- println "guidelines, ant-equivalent commands etc. under help/*; or type:"
- println ""
- helpFiles.each { section, path, sectionInfo ->
- println String.format(Locale.ROOT,
- " gradlew :help%-16s # %s", section, sectionInfo)
- }
- println ""
- println "For the impatient, build the project with 'gradlew assemble'"
- }
- }
-
- task allHelpFilesExit() {
- doFirst {
- helpFiles.each { section, path, sectionInfo ->
- if (!rootProject.file(path).exists()) {
- throw new GradleException("Help file missing: ${path} (correct help.gradle)")
- }
- }
- }
- }
-
- check.dependsOn allHelpFilesExit
-}
diff --git a/gradle/ide/eclipse.gradle b/gradle/ide/eclipse.gradle
deleted file mode 100644
index e58a73d8999..00000000000
--- a/gradle/ide/eclipse.gradle
+++ /dev/null
@@ -1,141 +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
-
-def resources = scriptResources(buildscript)
-
-configure(rootProject) {
- if (gradle.startParameter.taskNames.contains("eclipse")) {
- project.pluginManager.apply("java-base")
- project.pluginManager.apply("eclipse")
-
- def eclipseJavaVersion = propertyOrDefault("eclipse.javaVersion", deps.versions.minJava.get())
- def relativize = { other -> rootProject.rootDir.relativePath(other).toString() }
-
- eclipse {
- project {
- name = "Apache Lucene ${version}"
- }
-
- classpath {
- defaultOutputDir = file('build/eclipse')
-
- file {
- beforeMerged { classpath -> classpath.entries.removeAll { it.kind == "src" } }
-
- whenMerged { classpath ->
- 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 = []
- Set<File> jars = []
- 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) }
- }
- }
-
- // This is hacky - we take the resolved compile classpath and just
- // include JAR files from there. We should probably make it smarter
- // by looking at real dependencies. But then: this Eclipse configuration
- // doesn't really separate sources anyway so why bother.
- jars += prj.configurations.compileClasspath.resolve()
- jars += prj.configurations.testCompileClasspath.resolve()
- }
-
- classpath.entries += sources.sort().collect { name ->
- def sourceFolder = new SourceFolder(name, "build/eclipse/" + name)
- sourceFolder.setExcludes(["module-info.java"])
- return sourceFolder
- }
- classpath.entries += jars.unique().findAll { location -> location.isFile() && !(location.name ==~ /lucene-.*\.jar/) }.collect { location ->
- new LibEntry(location.toString())
- }
- }
- }
- }
-
- jdt {
- sourceCompatibility = eclipseJavaVersion
- targetCompatibility = eclipseJavaVersion
- javaRuntimeName = "JavaSE-$eclipseJavaVersion"
- }
- }
-
- task luceneEclipseJdt(type: Sync) {
- def errorMode = project.propertyOrDefault('eclipse.errors' ,'warning');
- 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 passing -Peclipse.errors=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
- )
- }
- }
-}
-
-public class LibEntry implements ClasspathEntry {
- private String path;
-
- LibEntry(String path) {
- this.path = path;
- }
-
- @Override
- String getKind() {
- return "lib"
- }
-
- @Override
- void appendNode(Node node) {
- node.appendNode("classpathentry", Map.of(
- "kind", "lib",
- "path", path
- ))
- }
-}
diff --git a/gradle/java/folder-layout.gradle b/gradle/java/folder-layout.gradle
deleted file mode 100644
index bc3da14a088..00000000000
--- a/gradle/java/folder-layout.gradle
+++ /dev/null
@@ -1,50 +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.
- */
-
-// Adapt to custom, legacy folder convention.
-allprojects {
- plugins.withType(JavaPlugin) {
- sourceSets {
- main.java.srcDirs = ['src/java']
- main.resources.srcDirs = ['src/resources']
- test.java.srcDirs = ['src/test']
- test.resources.srcDirs = ['src/test-files']
- }
-
- tasks.named('processTestResources').configure {
- from('src/test') {
- exclude '**/*.java'
- }
- }
-
- // if 'src/tools' exists, add it as a separate sourceSet.
- if (file('src/tools/java').exists()) {
- sourceSets {
- tools {
- java {
- srcDirs = ['src/tools/java']
- }
- }
- }
-
- configurations {
- // Inherit any dependencies from the main source set.
- toolsImplementation.extendsFrom implementation
- }
- }
- }
-}
\ No newline at end of file
diff --git a/gradle/java/jar-manifest.gradle b/gradle/java/jar-manifest.gradle
deleted file mode 100644
index 5e39358af75..00000000000
--- a/gradle/java/jar-manifest.gradle
+++ /dev/null
@@ -1,84 +0,0 @@
-import java.util.jar.JarFile
-import java.util.regex.Matcher
-
-/*
- * 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.
- */
-
-// Configures JAR manifest entries
-
-subprojects {
- // Declare these inline for now. Don't know if it makes sense to declare them
- // per-project.
- def title = "Lucene Search Engine: ${project.name}"
- def implementationTitle = "org.apache.lucene"
- def legaleseDir = project(":").projectDir
-
- // Apply the manifest to any JAR or WAR file created by any project.
- tasks.withType(Jar)
- .configureEach { task ->
- // Compute git status once on the root project prior to assembling manifest.
- dependsOn ":gitStatus"
-
- // Because git status is a task we must defer computing this
- // until status has been computed. We do this with a provider.
- def implementationVersion = provider {
- // LUCENE-9310: gitRev should always be there but IntelliJ does something
- // awkward on import and resolves provider properties even though task dependencies
- // have not been run yet?
- def gitRev = rootProject.hasProperty("gitRev") ? rootProject.gitRev : ""
-
- // For snapshot builds just include the project version and gitRev so that
- // JARs don't need to be recompiled just because the manifest has changed.
- if (snapshotBuild) {
- return "${project.version} ${gitRev} [snapshot build, details omitted]"
- } else {
- return "${project.version} ${gitRev} - ${buildDate} ${buildTime}"
- }
- }
-
- def manifestAttrs = [
- "Extension-Name" : implementationTitle,
-
- "Implementation-Vendor" : "The Apache Software Foundation",
- "Implementation-Title" : implementationTitle,
- "Implementation-Version": implementationVersion,
-
- "Specification-Vendor" : "The Apache Software Foundation",
- "Specification-Version" : project.baseVersion,
- "Specification-Title" : title,
-
- // Evaluate these properties lazily so that the defaults are applied properly.
- "X-Compile-Source-JDK" : "${-> project.sourceCompatibility}",
- "X-Compile-Target-JDK" : "${-> project.targetCompatibility}",
-
- "X-Build-JDK" : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})",
- "X-Build-OS" : "${System.properties['os.name']} ${System.properties['os.arch']} ${System.properties['os.version']}"
- ]
-
- manifest {
- attributes(manifestAttrs)
- }
-
- // Copy legalese into META-INF.
- metaInf {
- from(legaleseDir, {
- include "LICENSE.txt"
- include "NOTICE.txt"
- })
- }
- }
-}
diff --git a/gradle/java/javac.gradle b/gradle/java/javac.gradle
deleted file mode 100644
index 537769ea191..00000000000
--- a/gradle/java/javac.gradle
+++ /dev/null
@@ -1,89 +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.
- */
-
-// Configure Java project defaults.
-
-allprojects { project ->
- plugins.withType(JavaPlugin) {
- sourceCompatibility = rootProject.minJavaVersion
- targetCompatibility = rootProject.minJavaVersion
-
- // Use 'release' flag instead of 'source' and 'target'
- tasks.withType(JavaCompile) {
- options.compilerArgs += ["--release", rootProject.minJavaVersion.toString()]
- }
-
- // Configure warnings.
- // Use 'javac --help-lint' to get the supported list
- tasks.withType(JavaCompile) {
- options.encoding = "UTF-8"
- options.compilerArgs += [
- "-Xlint:auxiliaryclass",
- "-Xlint:cast",
- "-Xlint:classfile",
- "-Xlint:-deprecation",
- "-Xlint:dep-ann",
- "-Xlint:divzero",
- "-Xlint:empty",
- // TODO: uh-oh we have broken APIs.
- "-Xlint:-exports",
- "-Xlint:fallthrough",
- "-Xlint:finally",
- // TODO: untested
- "-Xlint:-missing-explicit-ctor",
- "-Xlint:module",
- "-Xlint:opens",
- "-Xlint:options",
- "-Xlint:overloads",
- "-Xlint:overrides",
- // TODO: some tests seem to have bad classpaths?
- // this check seems to be a good sanity check for gradle?
- "-Xlint:-path",
- "-Xlint:processing",
- "-Xlint:rawtypes",
- "-Xlint:removal",
- "-Xlint:requires-automatic",
- "-Xlint:requires-transitive-automatic",
- "-Xlint:-serial",
- "-Xlint:static",
- "-Xlint:strictfp",
- "-Xlint:synchronization",
- "-Xlint:text-blocks",
- "-Xlint:try",
- "-Xlint:unchecked",
- "-Xlint:varargs",
- "-Xlint:preview",
- "-Xdoclint:all/protected",
- "-Xdoclint:-missing",
- "-Xdoclint:-accessibility"
- ]
-
- if (project.path == ":lucene:benchmark-jmh") {
- // JMH benchmarks use JMH preprocessor and incubating modules.
- } else {
- // proc:none was added because of LOG4J2-1925 / JDK-8186647
- options.compilerArgs += [
- "-proc:none"
- ]
-
- if (propertyOrDefault("javac.failOnWarnings", true).toBoolean()) {
- options.compilerArgs += "-Werror"
- }
- }
- }
- }
-}
diff --git a/gradle/java/modules-debugging.gradle b/gradle/java/modules-debugging.gradle
deleted file mode 100644
index 52bc6fe1b3c..00000000000
--- a/gradle/java/modules-debugging.gradle
+++ /dev/null
@@ -1,84 +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.
- */
-
-// Debugging/ validation utilities and helpers to aid transition
-// to java modules.
-
-allprojects {
- plugins.withType(JavaPlugin) {
- // Show all non-empty package names
- tasks.register("showPackageNames", { task ->
- doFirst {
- listPackageNames(sourceSets).each { println(it) }
- }
- })
-
- tasks.register("showServiceProviders", { task ->
- doFirst {
- def services = listServices(sourceSets)
- services.each { entry -> {
- println(entry.key)
- entry.value.each { println(" ${it}") }
- }}
- }
- })
- }
-}
-
-/* Utility method to collect all package names in a source sets. */
-static def listPackageNames(SourceSetContainer sourceSets) {
- var pkgNameSet = [] as Set<String>
- sourceSets.main.each { sourceSet ->
- var dirs = sourceSet.allJava.srcDirTrees.collect { it.dir.toPath() }
- var pattern = new PatternSet()
- .include('**/*.java')
- .exclude('module-info.java')
- .exclude('**/package-info.java')
- sourceSet.allJava.matching(pattern).each {srcFile ->
- var srcPath = srcFile.toPath()
- var dir = dirs.find { srcPath.startsWith(it) }
- var pkgName = srcPath.subpath(dir.nameCount, srcPath.nameCount).parent.stream().map(Object::toString).collect(Collectors.joining('.'))
- pkgNameSet.add(pkgName)
- }
- }
- var pkgNames = pkgNameSet as List<String>
- pkgNames.sort()
- return pkgNames
-}
-
-/* Utility method to collect all service providers in a source sets. */
-static def listServices(SourceSetContainer sourceSets) {
- def services = [:] as Map<String, List<String>>
- sourceSets.main.each {sourceSet ->
- var pattern = new PatternSet().include('META-INF/services/*')
- sourceSet.resources.matching(pattern).each {file ->
- def serviceName = file.name
- def providers = []
- file.withReader { reader -> {
- reader.lines().each { l ->
- def line = l.trim()
- if (line != "" && !line.startsWith("#")) {
- def provider = line.replace('$', '.')
- providers.add(provider)
- }
- }
- }}
- services.put(serviceName, providers)
- }
- }
- return services
-}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 1ffa332f600..c2f729aa05a 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -26,8 +26,6 @@ icu4j = "77.1"
javacc = "7.0.13"
# analysis/ tokenizer grammars
jflex = "1.9.1"
-# gradle checkWorkingCopy support
-jgit = "7.3.0.202506031305-r"
# benchmark-jmh/ microbenchmarks
jmh = "1.37"
# spatial-extras/ support
@@ -79,7 +77,6 @@ hamcrest = { module = "org.hamcrest:hamcrest", version.ref = "hamcrest" }
icu4j = { module = "com.ibm.icu:icu4j", version.ref = "icu4j" }
javacc = { module = "net.java.dev.javacc:javacc", version.ref = "javacc" }
jflex = { module = "de.jflex:jflex", version.ref = "jflex" }
-jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" }
jmh-annprocess = { module = "org.openjdk.jmh:jmh-generator-annprocess", version.ref = "jmh" }
jmh-core = { module = "org.openjdk.jmh:jmh-core", version.ref = "jmh" }
jts = { module = "org.locationtech.jts:jts-core", version.ref = "jts" }
@@ -99,7 +96,7 @@ zstd = { module = "com.github.luben:zstd-jni", version.ref = "zstd" }
[plugins]
benmanes-versions = "com.github.ben-manes.versions:0.52.0"
-dependencychecks = "com.carrotsearch.gradle.dependencychecks:0.0.9"
+carrotsearch-buildinfra = "com.carrotsearch.gradle.buildinfra:0.0.12"
errorprone = "net.ltgt.errorprone:4.2.0"
forbiddenapis = "de.thetaphi.forbiddenapis:3.9"
jacocolog = "org.barfuin.gradle.jacocolog:3.1.0"
diff --git a/gradle/maven/maven-to-nexus-releases.gradle b/gradle/maven/maven-to-nexus-releases.gradle
deleted file mode 100644
index b08ccd12c65..00000000000
--- a/gradle/maven/maven-to-nexus-releases.gradle
+++ /dev/null
@@ -1,79 +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.
- */
-
-
-// Configure artifact push to apache nexus (releases repository).
-
-configure(rootProject) {
- ext {
- apacheNexusReleasesRepository = "https://repository.apache.org/service/local/staging/deploy/maven2"
- }
-
- // These access credentials must be passed by the release manager
- // (either on command-line, via the environment or via ~/.gradle.properties).
- def asfNexusUsername = propertyOrEnvOrDefault('asfNexusUsername', "ASF_NEXUS_USERNAME", null)
- def asfNexusPassword = propertyOrEnvOrDefault('asfNexusPassword', "ASF_NEXUS_PASSWORD", null)
-
- task mavenToApacheReleases() {
- group "Distribution"
- description "Publish Lucene Maven artifacts to Apache Releases repository: ${apacheNexusReleasesRepository}"
-
- dependsOn rootProject.ext.mavenProjects.collect {
- it.tasks.matching { it.name == "publishSignedJarsPublicationToApacheReleasesRepository" }
- }
- }
-
- task checkReleasesRepositoryPushPreconditions() {
- doFirst {
- // Make sure we're pushing a release version. The release repository
- // does not accept snapshots and returns cryptic errors upon trying.
- if (snapshotBuild) {
- throw new GradleException("ASF releases repository will not accept a snapshot version: ${rootProject.version}")
- }
-
- // Make sure access credentials have been passed.
- if (asfNexusUsername == null || asfNexusPassword == null) {
- throw new GradleException("asfNexusUsername or asfNexusPassword is empty: these are required to publish to " +
- " ASF Nexus.")
- }
- }
- }
-
- configure(rootProject.ext.mavenProjects) { Project project ->
- // Make sure any actual publication task is preceded by precondition checks.
- tasks.matching { it.name ==~ /publish.+ToApacheReleasesRepository/ }.all {
- dependsOn rootProject.tasks.checkReleasesRepositoryPushPreconditions
- }
-
- // Configure the release repository.
- plugins.withType(PublishingPlugin) {
- publishing {
- repositories {
- maven {
- name = "ApacheReleases"
- url = apacheNexusReleasesRepository
-
- credentials {
- username asfNexusUsername
- password asfNexusPassword
- }
- }
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/gradle/maven/maven-to-nexus-snapshots.gradle b/gradle/maven/maven-to-nexus-snapshots.gradle
deleted file mode 100644
index cf0fb4a7516..00000000000
--- a/gradle/maven/maven-to-nexus-snapshots.gradle
+++ /dev/null
@@ -1,76 +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.
- */
-
-
-// Configure artifact push to apache nexus (snapshots repository, CI job)
-
-configure(rootProject) {
- ext {
- apacheNexusSnapshotsRepository = "https://repository.apache.org/content/repositories/snapshots"
- }
-
- // These access credentials are typically passed by the CI job.
- def asfNexusUsername = propertyOrEnvOrDefault('asfNexusUsername', "ASF_NEXUS_USERNAME", null)
- def asfNexusPassword = propertyOrEnvOrDefault('asfNexusPassword', "ASF_NEXUS_PASSWORD", null)
-
- task mavenToApacheSnapshots() {
- group "Distribution"
- description "Publish Lucene Maven artifacts to Apache Snapshots repository: ${apacheNexusSnapshotsRepository}"
-
- dependsOn rootProject.ext.mavenProjects.collect {
- it.tasks.matching { it.name == "publishJarsPublicationToApacheSnapshotsRepository" }
- }
- }
-
- task checkSnapshotsRepositoryPushPreconditions() {
- doFirst {
- // Make sure we're pushing a snapshot version.
- if (!snapshotBuild) {
- throw new GradleException("ASF snapshots repository will not accept a non-snapshot version: ${rootProject.version}")
- }
-
- // Make sure access credentials have been passed.
- if (asfNexusUsername == null || asfNexusPassword == null) {
- throw new GradleException("asfNexusUsername or asfNexusPassword is empty: these are required to publish to " +
- " ASF Nexus.")
- }
- }
- }
-
- configure(rootProject.ext.mavenProjects) { Project project ->
- // Make sure any actual publication task is preceded by precondition checks.
- tasks.matching { it.name ==~ /publish.+ToApacheSnapshotsRepository/ }.all {
- dependsOn rootProject.tasks.checkSnapshotsRepositoryPushPreconditions
- }
-
- plugins.withType(PublishingPlugin) {
- publishing {
- repositories {
- maven {
- name = "ApacheSnapshots"
- url = apacheNexusSnapshotsRepository
-
- credentials {
- username asfNexusUsername
- password asfNexusPassword
- }
- }
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/gradle/maven/publications.gradle b/gradle/maven/publications.gradle
deleted file mode 100644
index 2fae5964b09..00000000000
--- a/gradle/maven/publications.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.
- */
-
-/*
- * This script configures aspects related to all project publications,
- * this includes:
- *
- * - configuring maven artifacts,
- * - setting up target maven repositories for publications to end up on,
- * - configuring binary and source release artifacts,
- * - other concerns related to publishing artifacts (signing, checksums).
- */
-
-//
-// An explicit list of projects to publish as Maven artifacts.
-//
-configure(rootProject) {
- ext {
- mavenProjects = project(":lucene").subprojects.findAll {subproject ->
- def excluded = [
- // Exclude distribution assembly, tests & documentation.
- ":lucene:distribution",
- ":lucene:documentation",
- // Exclude the parent container project for analysis modules (no artifacts).
- ":lucene:analysis",
- // Exclude the native module.
- ":lucene:misc:native",
- // Exclude test fixtures.
- ":lucene:spatial-test-fixtures",
- // Exclude JMH benchmarks.
- ":lucene:benchmarks-jmh",
- ]
-
- // Exclude all subprojects that are modular test projects and those explicitly
- // excluded above.
- return !(subproject.path.endsWith(".tests") || subproject.path in excluded)
- }
- }
-}
-
-// Configure the signing plugin.
-apply from: buildscript.sourceFile.toPath().resolveSibling("signing.gradle")
-
-// Configure projects for publishing Maven artifacts and set up metadata.
-apply from: buildscript.sourceFile.toPath().resolveSibling("publications-maven.gradle")
-
-// Configure on-demand maven publishing into ~/.m2 for developers' convenience.
-apply from: buildscript.sourceFile.toPath().resolveSibling("maven-to-local-m2.gradle")
-
-// Configure artifact push to apache nexus (snapshots repository, CI job).
-apply from: buildscript.sourceFile.toPath().resolveSibling("maven-to-nexus-snapshots.gradle")
-
-// Configure artifact push to apache nexus (releases repository).
-apply from: buildscript.sourceFile.toPath().resolveSibling("maven-to-nexus-releases.gradle")
diff --git a/gradle/maven/signing.gradle b/gradle/maven/signing.gradle
deleted file mode 100644
index 5b51f54b81d..00000000000
--- a/gradle/maven/signing.gradle
+++ /dev/null
@@ -1,38 +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.
- */
-
-
-// Optionally, switch to using an external GPG command, using it's configured gpg-agent for key management
-if (propertyOrDefault("useGpg", null) != null) {
-
- // Do this check before 'useGpgCmd()' (and once), otherwise gradle will fail with a confusing error about 'signatory.keyId'
- //
- // 'signatory.keyId' is an implementation detail of the SigningPlugin that it populates from 'signing.gnupg.keyName' when useGpgCmd()
- // is used -- but does not explain in the error produced if 'signing.gnupg.keyName' is not set.
- def propName = 'signing.gnupg.keyName'
- if (propertyOrDefault(propName, null) == null) {
- throw new GradleException("'$propName' property must be set when using external GPG via 'useGpg', please see help/publishing.txt")
- }
-
- rootProject.allprojects {
- plugins.withType(SigningPlugin) {
- signing {
- useGpgCmd()
- }
- }
- }
-}
diff --git a/gradle/generation/extract-jdk-apis/ExtractJdkApis.java b/gradle/regenerate/extract-jdk-apis/ExtractJdkApis.java
similarity index 100%
rename from gradle/generation/extract-jdk-apis/ExtractJdkApis.java
rename to gradle/regenerate/extract-jdk-apis/ExtractJdkApis.java
diff --git a/gradle/generation/icu/GenerateCaseFolding.groovy b/gradle/regenerate/icu/GenerateCaseFolding.groovy
similarity index 100%
rename from gradle/generation/icu/GenerateCaseFolding.groovy
rename to gradle/regenerate/icu/GenerateCaseFolding.groovy
diff --git a/gradle/generation/icu/GenerateUnicodeProps.groovy b/gradle/regenerate/icu/GenerateUnicodeProps.groovy
similarity index 100%
rename from gradle/generation/icu/GenerateUnicodeProps.groovy
rename to gradle/regenerate/icu/GenerateUnicodeProps.groovy
diff --git a/gradle/generation/jflex/htmlentity.py b/gradle/regenerate/jflex/htmlentity.py
similarity index 100%
rename from gradle/generation/jflex/htmlentity.py
rename to gradle/regenerate/jflex/htmlentity.py
diff --git a/gradle/generation/jflex/skeleton.default.txt b/gradle/regenerate/jflex/skeleton.default.txt
similarity index 100%
rename from gradle/generation/jflex/skeleton.default.txt
rename to gradle/regenerate/jflex/skeleton.default.txt
diff --git a/gradle/generation/jflex/skeleton.disable.buffer.expansion.txt b/gradle/regenerate/jflex/skeleton.disable.buffer.expansion.txt
similarity index 100%
rename from gradle/generation/jflex/skeleton.disable.buffer.expansion.txt
rename to gradle/regenerate/jflex/skeleton.disable.buffer.expansion.txt
diff --git a/gradle/generation/moman/createLevAutomata.py b/gradle/regenerate/moman/createLevAutomata.py
similarity index 100%
rename from gradle/generation/moman/createLevAutomata.py
rename to gradle/regenerate/moman/createLevAutomata.py
diff --git a/gradle/generation/moman/gen_BulkOperation.py b/gradle/regenerate/moman/gen_BulkOperation.py
similarity index 100%
rename from gradle/generation/moman/gen_BulkOperation.py
rename to gradle/regenerate/moman/gen_BulkOperation.py
diff --git a/gradle/generation/moman/gen_Packed64SingleBlock.py b/gradle/regenerate/moman/gen_Packed64SingleBlock.py
similarity index 100%
rename from gradle/generation/moman/gen_Packed64SingleBlock.py
rename to gradle/regenerate/moman/gen_Packed64SingleBlock.py
diff --git a/gradle/generation/snowball/snowball.sh b/gradle/regenerate/snowball/snowball.sh
similarity index 100%
rename from gradle/generation/snowball/snowball.sh
rename to gradle/regenerate/snowball/snowball.sh
diff --git a/gradle/template.gradle.properties b/gradle/template.gradle.properties
index 0d0828a6d55..48e2f5e00f1 100644
--- a/gradle/template.gradle.properties
+++ b/gradle/template.gradle.properties
@@ -49,6 +49,9 @@
# tests.minheapsize=512m
# tests.jvmargs=-XX:+UseParallelGC -XX:TieredStopAtLevel=1 -XX:ActiveProcessorCount=1
#
+# See help/localSettings.txt for ways to discover which build options are available and
+# how you can tweak them.
+#
#################
# Gradle Daemon #
#################
@@ -102,8 +105,5 @@ tests.jvms=@TEST_JVMS@
org.gradle.java.installations.auto-download=true
# Set these to enable automatic JVM location discovery.
-org.gradle.java.installations.fromEnv=JAVA23_HOME,RUNTIME_JAVA_HOME
+org.gradle.java.installations.fromEnv=JAVA24_HOME,RUNTIME_JAVA_HOME
#org.gradle.java.installations.paths=(custom paths)
-
-# Opt out of gradle enterprise build scan plugin entire.
-# gradle.ge=false
diff --git a/gradle/testing/defaults-tests.gradle b/gradle/testing/defaults-tests.gradle
deleted file mode 100644
index 22d3f9530da..00000000000
--- a/gradle/testing/defaults-tests.gradle
+++ /dev/null
@@ -1,239 +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.taskdefs.condition.Os
-import org.apache.tools.ant.types.Commandline
-import org.gradle.api.tasks.testing.logging.*
-
-def resources = scriptResources(buildscript)
-def verboseModeHookInstalled = false
-
-allprojects {
- plugins.withType(JavaPlugin) {
- project.ext {
- // This array will collect all test options, including default values and option description.
- // The actual values of these properties (defaults, project properties) are resolved lazily after evaluation
- // completes.
- // [propName: 'tests.foo', value: "bar", description: "Sets foo in tests."],
- testOptions = [
- // asserts, debug output.
- [propName: 'tests.verbose', value: false, description: "Enables verbose mode (emits full test outputs immediately)."],
- [propName: 'tests.workDir',
- value: { -> project.relativePath(file("${buildDir}/tmp/tests-tmp")) },
- description: "Working directory for forked test JVMs",
- includeInReproLine: false
- ],
- // JVM settings
- [propName: 'tests.minheapsize', value: "256m", description: "Minimum heap size for test JVMs"],
- [propName: 'tests.heapsize', value: "512m", description: "Heap size for test JVMs"],
- // Test forks
- [propName: 'tests.jvms',
- value: { -> ((int) Math.max(1, Math.min(Runtime.runtime.availableProcessors() / 2.0, 4.0))) },
- description: "Number of forked test JVMs"],
- [propName: 'tests.haltonfailure',
- value: true,
- description: "Halt processing on test failure.",
- includeInReproLine: false
- ],
- [propName: 'tests.jvmargs',
- value: { -> envOrDefault("TEST_JVM_ARGS", (isCIBuild || testsDefaultVectorizationRequested()) ? "" : "-XX:TieredStopAtLevel=1 -XX:+UseParallelGC -XX:ActiveProcessorCount=1") },
- description: "Arguments passed to each forked JVM."],
- // Other settings.
- [propName: 'tests.neverUpToDate', value: true,
- description: "Make test tasks always fail the up-to-date checks (rerun) even if the inputs have not changed."],
- ]
-
- // Resolves test option's value.
- resolvedTestOption = { propName ->
- def option = testOptions.find { entry -> entry.propName == propName }
- if (option == null) {
- throw new GradleException("No such test option: " + propName)
- }
- return propertyOrDefault(option.propName, option.value)
- }
-
- testsDefaultVectorizationRequested = { -> Boolean.parseBoolean(resolvedTestOption('tests.defaultvectorization') as String) }
-
- testsCwd = file("${buildDir}/tmp/tests-cwd")
- testsTmpDir = file(resolvedTestOption("tests.workDir"))
-
- commonDir = project(":lucene").projectDir
- }
-
- def verboseMode = resolvedTestOption("tests.verbose").toBoolean()
-
- // If we're running in verbose mode and:
- // 1) worker count > 1
- // 2) number of 'test' tasks in the build is > 1
- // then the output would very likely be mangled on the
- // console. Fail and let the user know what to do.
- if (verboseMode && !verboseModeHookInstalled) {
- verboseModeHookInstalled = true
- if (gradle.startParameter.maxWorkerCount > 1) {
- gradle.taskGraph.whenReady { graph ->
- def testTasks = graph.allTasks.findAll { task -> task instanceof Test }
- if (testTasks.size() > 1) {
- throw new GradleException("Run your tests in verbose mode only with --max-workers=1 option passed to gradle.")
- }
- }
- }
- }
-
- tasks.withType(Test) {
- ext {
- testOutputsDir = file("${reports.junitXml.outputLocation.get()}/outputs")
- }
-
- // LUCENE-9660: Make it possible to always rerun tests, even if they're incrementally up-to-date.
- if (resolvedTestOption("tests.neverUpToDate").toBoolean()) {
- outputs.upToDateWhen { false }
- }
-
- maxParallelForks = resolvedTestOption("tests.jvms") as Integer
- if (verboseMode && maxParallelForks != 1) {
- logger.lifecycle("tests.jvm forced to 1 in verbose mode.")
- maxParallelForks = 1
- }
-
- workingDir testsCwd
- useJUnit()
-
- minHeapSize = resolvedTestOption("tests.minheapsize")
- maxHeapSize = resolvedTestOption("tests.heapsize")
-
- ignoreFailures = resolvedTestOption("tests.haltonfailure").toBoolean() == false
-
- // Up to JDK-15 we have to enforce --illegal-access=deny, because we want no code to access
- // JDK internals; JDK-16 and later will default to deny, see https://openjdk.java.net/jeps/396:
- if (rootProject.runtimeJavaVersion < JavaVersion.VERSION_16) {
- jvmArgs '--illegal-access=deny'
- }
-
- // Lucene needs to optional modules at runtime, which we want to enforce for testing
- // (if the runner JVM does not support them, it will fail tests):
- jvmArgs '--add-modules', 'jdk.management'
-
- // dump heap on OOM.
- jvmArgs "-XX:+HeapDumpOnOutOfMemoryError"
-
- // Enable the vector incubator module on supported Java versions:
- def prop = propertyOrDefault("org.apache.lucene.vectorization.upperJavaFeatureVersion", "1") as String
- def v = JavaVersion.toVersion(Integer.parseInt(prop)).majorVersion
- if (rootProject.vectorIncubatorJavaVersions.contains(rootProject.runtimeJavaVersion) ||
- rootProject.runtimeJavaVersion.majorVersion <= v) {
- jvmArgs '--add-modules', 'jdk.incubator.vector'
- if (rootProject.runtimeJavaVersion.majorVersion <= v) {
- systemProperty 'org.apache.lucene.vectorization.upperJavaFeatureVersion', v
- }
- }
-
- jvmArgs '--enable-native-access=' + (project.path in [
- ':lucene:core',
- ':lucene:codecs',
- ":lucene:distribution.tests",
- ":lucene:test-framework"
- ] ? 'ALL-UNNAMED' : 'org.apache.lucene.core')
-
- def loggingConfigFile = layout.projectDirectory.file("${resources}/logging.properties")
- def tempDir = layout.projectDirectory.dir(testsTmpDir.toString())
- jvmArgumentProviders.add(
- new LoggingFileArgumentProvider(
- loggingConfigFile: loggingConfigFile,
- tempDir: tempDir
- )
- )
-
- systemProperty 'java.awt.headless', 'true'
- systemProperty 'jdk.map.althashing.threshold', '0'
-
- if (!Os.isFamily(Os.FAMILY_WINDOWS)) {
- systemProperty 'java.security.egd', 'file:/dev/./urandom'
- }
-
- // jetty-related.
- systemProperty 'jetty.testMode', '1'
- systemProperty 'jetty.insecurerandom', '1'
-
- // Turn jenkins blood red for hashmap bugs, even on jdk7
- systemProperty 'jdk.map.althashing.threshold', '0'
-
- // Pass these to RandomizedRunner so that it doesn't attempt to set them.
- systemProperty 'junit4.childvm.count', '1'
- systemProperty 'junit4.childvm.id', '0'
-
- // Set up cwd and temp locations.
- systemProperty("java.io.tmpdir", testsTmpDir)
- doFirst {
- testsCwd.mkdirs()
- testsTmpDir.mkdirs()
- }
-
- // Disable HTML report generation. The reports are big and slow to generate.
- reports.html.required = false
-
- // Set up logging.
- testLogging {
- events TestLogEvent.FAILED
- exceptionFormat TestExceptionFormat.FULL
- showExceptions true
- showCauses true
- showStackTraces true
- stackTraceFilters.clear()
- showStandardStreams false
- }
-
- // Disable automatic test class detection, rely on class names only. This is needed for testing
- // against JDKs where the bytecode is unparseable by Gradle, for example.
- // We require all tests to start with Test*, this simplifies include patterns greatly.
- scanForTestClasses = false
- include '**/Test*.class'
- exclude '**/*$*'
-
- // Set up custom test output handler.
- doFirst {
- project.delete testOutputsDir
- }
-
- def spillDir = getTemporaryDir().toPath()
- def listener = buildinfra.newErrorReportingTestListener(test.testLogging, spillDir, testOutputsDir.toPath(), verboseMode)
- addTestOutputListener(listener)
- addTestListener(listener)
-
- doFirst {
- // Print some diagnostics about locations used.
- logger.info("Test folders for {}: cwd={}, tmp={}", project.path, testsCwd, testsTmpDir)
- }
- }
- }
-}
-
-class LoggingFileArgumentProvider implements CommandLineArgumentProvider {
- @InputFile
- @PathSensitive(PathSensitivity.RELATIVE)
- RegularFile loggingConfigFile
-
- @Internal
- Directory tempDir
-
- @Override
- Iterable<String> asArguments() {
- [
- "-Djava.util.logging.config.file=${loggingConfigFile.getAsFile()}",
- "-DtempDir=${tempDir.getAsFile()}"
- ]
- }
-}
diff --git a/gradle/testing/failed-tests-at-end.gradle b/gradle/testing/failed-tests-at-end.gradle
deleted file mode 100644
index c514046b029..00000000000
--- a/gradle/testing/failed-tests-at-end.gradle
+++ /dev/null
@@ -1,59 +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.
- */
-
-// Display all failed tests at the end of the build.
-
-def failedTests = []
-
-allprojects {
- tasks.withType(Test) { Test task ->
- afterTest { desc, result ->
- if (result.resultType == TestResult.ResultType.FAILURE) {
- failedTests << [
- "name": "${desc.className}.${desc.name}",
- "project": "${test.project.path}",
- "output": file("${task.testOutputsDir}/${buildinfra.getOutputLogName(desc.parent)}"),
- "reproduce": "gradlew ${project.path}:test --tests \"${desc.className}.${desc.name}\" ${task.project.testOptionsForReproduceLine}"
- ]
- }
- }
-
- afterSuite { desc, result ->
- if (result.exceptions) {
- failedTests << [
- "name": "${desc.name}",
- "project": "${test.project.path}",
- "output": file("${task.testOutputsDir}/${buildinfra.getOutputLogName(desc)}"),
- "reproduce": "gradlew ${project.path}:test --tests \"${desc.name}\" ${task.project.testOptionsForReproduceLine}"
- ]
- }
- }
- }
-}
-
-gradle.buildFinished { result ->
- if (failedTests) {
- def formatted = failedTests
- .sort { a, b -> b.project.compareTo(a.project) }
- .collect { e -> String.format(Locale.ROOT,
- " - %s (%s)\n Test output: %s\n Reproduce with: %s\n",
- e.name, e.project, e.output, e.reproduce) }
- .join("\n")
-
- logger.error("\nERROR: The following test(s) have failed:\n${formatted}")
- }
-}
diff --git a/gradle/testing/defaults-tests/logging.properties b/gradle/testing/logging.properties
similarity index 100%
rename from gradle/testing/defaults-tests/logging.properties
rename to gradle/testing/logging.properties
diff --git a/gradle/testing/profiling.gradle b/gradle/testing/profiling.gradle
deleted file mode 100644
index 88284fb5454..00000000000
--- a/gradle/testing/profiling.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 recordings = files()
-
-allprojects {
- plugins.withType(JavaPlugin) {
- project.ext {
- testOptions += [
- [propName: 'tests.profile', value: false, description: "Enable Java Flight Recorder profiling."]
- ]
- }
-
- if (resolvedTestOption("tests.profile").toBoolean()) {
- if (rootProject.hasJavaFlightRecorder) {
- tasks.withType(Test) {
- 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.')
- }
- }
- }
-}
-
-gradle.buildFinished {
- if (!recordings.isEmpty()) {
- def pr = org.apache.lucene.gradle.ProfileResults;
- pr.printReport(recordings.getFiles().collect { it.toString() },
- propertyOrDefault(pr.MODE_KEY, pr.MODE_DEFAULT) as String,
- Integer.parseInt(propertyOrDefault(pr.STACKSIZE_KEY, pr.STACKSIZE_DEFAULT)),
- Integer.parseInt(propertyOrDefault(pr.COUNT_KEY, pr.COUNT_DEFAULT)),
- Boolean.parseBoolean(propertyOrDefault(pr.LINENUMBERS_KEY, pr.LINENUMBERS_DEFAULT)))
- }
-}
diff --git a/gradle/testing/randomization.gradle b/gradle/testing/randomization.gradle
deleted file mode 100644
index 185cd0872a9..00000000000
--- a/gradle/testing/randomization.gradle
+++ /dev/null
@@ -1,288 +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.
- */
-
-//
-// Configure test randomization seeds and derived test properties.
-//
-
-import java.nio.file.*
-import com.carrotsearch.randomizedtesting.SeedUtils
-import com.carrotsearch.randomizedtesting.generators.RandomPicks
-import org.apache.tools.ant.types.Commandline
-
-buildscript {
- repositories {
- mavenCentral()
- }
-
- dependencies {
- classpath deps.randomizedtesting.runner
- }
-}
-
-def resources = scriptResources(buildscript)
-
-// Pick the "root" seed from which everything else is derived.
-configure(rootProject) {
- ext {
- rootSeed = propertyOrDefault('tests.seed', String.format("%08X", new Random().nextLong()))
- rootSeedUserProvided = (propertyOrDefault('tests.seed', null) != null)
- rootSeedLong = SeedUtils.parseSeedChain(rootSeed)[0]
- projectSeedLong = rootSeedLong ^ project.path.hashCode()
- }
-
- task randomizationInfo() {
- doFirst {
- logger.lifecycle("Running tests with randomization seed: tests.seed=${rootSeed}")
- }
- }
-}
-
-// Any test task will trigger display of randomization settings.
-allprojects {
- tasks.withType(Test) { task ->
- task.dependsOn rootProject.randomizationInfo
- }
-}
-
-// Configure test property defaults and their descriptions.
-allprojects {
- plugins.withType(JavaPlugin) {
- project.ext {
- String randomVectorSize = RandomPicks.randomFrom(new Random(projectSeedLong), ["default", "128", "256", "512"])
- testOptions += [
- // seed, repetition and amplification.
- [propName: 'tests.seed', value: { -> rootSeed }, description: "Sets the master randomization seed."],
- [propName: 'tests.iters', value: null, description: "Duplicate (re-run) each test case N times."],
- [propName: 'tests.multiplier', value: null, description: "Value multiplier for randomized tests."],
- [propName: 'tests.maxfailures', value: null, description: "Skip tests after a given number of failures."],
- [propName: 'tests.timeoutSuite', value: null, description: "Timeout (in millis) for an entire suite."],
- [propName: 'tests.failfast', value: "false", description: "Stop the build early on failure.", buildOnly: true],
- // asserts, debug output.
- [propName: 'tests.asserts', value: "true", description: "Enables or disables assertions mode."],
- [propName: 'tests.infostream', value: false, description: "Enables or disables infostream logs."],
- [propName: 'tests.leaveTemporary', value: false, description: "Leave temporary directories after tests complete."],
- [propName: 'tests.useSecurityManager',
- value: { -> rootProject.ext.runtimeJavaVersion <= JavaVersion.VERSION_23 ? 'true' : 'false' },
- description: "Control security manager in tests.", buildOnly: true],
- // component randomization
- [propName: 'tests.codec', value: "random", description: "Sets the codec tests should run with."],
- [propName: 'tests.directory', value: "random", description: "Sets the Directory implementation tests should run with."],
- [propName: 'tests.postingsformat', value: "random", description: "Sets the postings format tests should run with."],
- [propName: 'tests.docvaluesformat', value: "random", description: "Sets the doc values format tests should run with."],
- [propName: 'tests.locale', value: "random", description: "Sets the default locale tests should run with."],
- [propName: 'tests.timezone', value: "random", description: "Sets the default time zone tests should run with."],
- // filtering
- [propName: 'tests.filter', value: null, description: "Applies a test filter (see :helpTests)."],
- [propName: 'tests.nightly', value: false, description: "Enables or disables @Nightly tests."],
- [propName: 'tests.weekly', value: false, description: "Enables or disables @Weekly tests."],
- [propName: 'tests.monster', value: false, description: "Enables or disables @Monster tests."],
- [propName: 'tests.awaitsfix', value: null, description: "Enables or disables @AwaitsFix tests."],
- [propName: 'tests.gui',
- value: { ->
- return rootProject.ext.isCIBuild
- },
- description: "Enables or disables @RequiresGUI tests."],
- [propName: 'tests.file.encoding',
- value: { ->
- RandomPicks.randomFrom(new Random(projectSeedLong), ["US-ASCII", "ISO-8859-1", "UTF-8"])
- },
- description: "Sets the default file.encoding on test JVM.", buildOnly: true],
- // Test data file used.
- [propName: 'tests.linedocsfile', value: 'europarl.lines.txt.gz', description: "Test data file path."],
- // miscellaneous; some of them very weird.
- [propName: 'tests.LUCENE_VERSION', value: baseVersion, description: "Base Lucene version."],
- [propName: 'tests.bwcdir', value: null, description: "Data for backward-compatibility indexes."],
- // vectorization related
- [propName: 'tests.vectorsize',
- value: { -> testsDefaultVectorizationRequested() ? 'default' : randomVectorSize },
- description: "Sets preferred vector size in bits."],
- [propName: 'tests.forceintegervectors',
- value: { -> testsDefaultVectorizationRequested() ? false : (randomVectorSize != 'default') },
- description: "Forces use of integer vectors even when slow."],
- [propName: 'tests.defaultvectorization', value: false,
- description: "Uses defaults for running tests with correct JVM settings to test Panama vectorization (tests.jvmargs, tests.vectorsize, tests.forceintegervectors)."],
- ]
- }
- }
-}
-
-// Resolve test option values after all evaluation is complete.
-allprojects {
- plugins.withType(JavaPlugin) {
- configurations {
- secManagerExclusions
- }
- dependencies {
- secManagerExclusions ( deps.randomizedtesting.runner, {
- exclude group: "junit"
- })
- secManagerExclusions ( deps.junit, {
- exclude group: "org.hamcrest"
- })
- }
-
- afterEvaluate {
- project.ext.testOptionsResolved = testOptions.findAll { opt ->
- propertyOrDefault(opt.propName, opt.value) != null
- }.collectEntries { opt ->
- [(opt.propName): Objects.toString(resolvedTestOption(opt.propName))]
- }
-
- // Compute the "reproduce with" string.
- project.ext.testOptionsForReproduceLine = testOptions.findAll { opt ->
- if (opt["includeInReproLine"] == false) {
- return false
- }
-
- def defValue = Objects.toString(opt.value, null)
- def value = testOptionsResolved[opt.propName]
- return defValue != value
- }.collect { opt ->
- Commandline.quoteArgument("-P" + opt.propName + "=" + testOptionsResolved[opt.propName])
- }.join(" ")
-
- // leaving temporary folder option has multiple aliases...
- if ([
- "tests.leaveTemporary",
- "tests.leavetemporary",
- "tests.leavetmpdir",
- ].find { prop ->
- def v = Boolean.parseBoolean(propertyOrDefault(prop, "false"))
- if (v) {
- logger.lifecycle("Update your code to use the official 'tests.leaveTemporary' option (you used '${prop}').")
- }
- return v
- }) {
- testOptionsResolved['tests.leaveTemporary'] = "true"
- }
-
- // Append resolved test properties to the test task.
- tasks.withType(Test) { Test task ->
- // TODO: we could remove some options that are only relevant to the build environment
- // and not the test JVM itself.
- systemProperties testOptionsResolved
-
- jvmArgs Commandline.translateCommandline(testOptionsResolved['tests.jvmargs'])
-
- if (Boolean.parseBoolean(testOptionsResolved['tests.asserts'])) {
- jvmArgs("-ea", "-esa")
- } else {
- enableAssertions = false
- }
-
- if (Boolean.parseBoolean(testOptionsResolved["tests.failfast"])) {
- failFast true
- }
-
- // Enable security manager, if requested. We could move the selection of security manager and security policy
- // to each project's build/ configuration but it seems compact enough to keep it here for now.
- def securityArgumentProvider = new SecurityArgumentProvider()
- securityArgumentProvider.commonDir = project(":lucene").layout.projectDirectory
- securityArgumentProvider.otherProperties = project.objects.mapProperty(String, String)
-
- if (Boolean.parseBoolean(testOptionsResolved["tests.useSecurityManager"])) {
- if (project.path.endsWith(".tests")) {
- // LUCENE-10301: for now, do not use the security manager for modular tests (test framework is not available).
- } else if (project.path.startsWith(":lucene")) {
- systemProperty 'java.security.manager', "org.apache.lucene.tests.util.TestSecurityManager"
- securityArgumentProvider.javaSecurityPolicy = layout.projectDirectory.file("${resources}/policies/tests.policy")
- }
- jvmArgumentProviders.add(securityArgumentProvider)
-
- def gradleUserHome = project.gradle.getGradleUserHomeDir()
- systemProperty 'gradle.lib.dir', Paths.get(project.class.location.toURI()).parent.toAbsolutePath().toString().replace('\\', '/')
- systemProperty 'gradle.worker.jar', Paths.get("${gradleUserHome}/caches/${gradle.gradleVersion}/workerMain/gradle-worker.jar").toAbsolutePath().toString()
- systemProperty 'gradle.user.home', gradleUserHome.toPath().toAbsolutePath().toString()
-
- securityArgumentProvider.otherProperties.put("randomizedtesting.jar", project.provider { ->
- return configurations.secManagerExclusions.resolve().find { it.name.startsWith("randomizedtesting-runner-") }.absolutePath
- })
- securityArgumentProvider.otherProperties.put("junit.jar", project.provider { ->
- return configurations.secManagerExclusions.resolve().find { it.name.startsWith("junit-") }.absolutePath
- })
- securityArgumentProvider.otherProperties.put("lucene.test.framework", project(":lucene:test-framework").layout.buildDirectory.get().asFile.absolutePath)
- }
-
- doFirst {
- logger.debug("Will use test opts:\n" + testOptionsResolved.collect {k,v -> "${k}: ${v}"}.sort().join("\n"))
- }
- }
- }
- }
-}
-
-// Add a helper task to display resolved test property values with their defaults
-// and descriptions.
-allprojects {
- plugins.withType(JavaPlugin) {
- task testOpts() {
- group = 'Help (developer guides and hints)'
- description = "Display values of randomization settings for a given seed"
-
- doFirst {
- println "Test options for project ${project.path} and seed \"${rootSeed}\":"
-
- testOptions.sort { a, b -> a.propName.compareTo(b.propName) }.each { opt ->
- def defValue
- def computedValue = false
- if (opt.value instanceof Closure) {
- defValue = Objects.toString(opt.value(), null)
- computedValue = true
- } else {
- defValue = Objects.toString(opt.value, null)
- }
-
- def value = testOptionsResolved[opt.propName]
- println String.format(Locale.ROOT,
- "%s%-24s = %-8s # %s",
- (defValue != value ? "! " : computedValue ? "C " : " "),
- opt.propName,
- value,
- (computedValue ? "(!= default: computed) " : (defValue != value ? "(!= default: ${defValue}) " : "")) + opt.description)
- }
- }
- }
- }
-}
-
-class SecurityArgumentProvider implements CommandLineArgumentProvider {
- @Internal
- Directory commonDir
-
- @InputFile
- @Optional
- @PathSensitive(PathSensitivity.RELATIVE)
- RegularFile javaSecurityPolicy
-
- @Input
- MapProperty<String, String> otherProperties
-
- @Override
- Iterable<String> asArguments() {
- def args = ["-Dcommon.dir=${commonDir.getAsFile()}"]
- if (javaSecurityPolicy) {
- args.add("-Djava.security.policy=${javaSecurityPolicy.getAsFile()}")
- }
-
- otherProperties.getOrElse(Map.of()).forEach { key, value ->
- args.add("-D${key}=${value}")
- }
-
- return args
- }
-}
diff --git a/gradle/testing/randomization/policies/tests.policy b/gradle/testing/randomization/policies/tests.policy
deleted file mode 100644
index f8e09ba0366..00000000000
--- a/gradle/testing/randomization/policies/tests.policy
+++ /dev/null
@@ -1,123 +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.
- */
-
-// Policy file for lucene tests. Please keep minimal and avoid wildcards.
-
-grant {
- // let TestIndexWriterOnJRECrash fork its jvm
- permission java.io.FilePermission "${java.home}${/}-", "read,execute";
-
- // test-files/ resources
- permission java.io.FilePermission "${common.dir}${/}-", "read";
- // classpath-as-file, eg getDataPath, and only rarely (this acts like a JDK bug...)
- permission java.io.FilePermission ".", "read";
-
- // write only to sandbox
- permission java.io.FilePermission "${tests.linedocsfile}", "read";
- permission java.io.FilePermission "${java.io.tmpdir}", "read,write";
- permission java.io.FilePermission "${java.io.tmpdir}${/}-", "read,write,delete";
-
- // misc HardlinkCopyDirectoryWrapper needs this to test if hardlinks can be created
- permission java.nio.file.LinkPermission "hard";
-
- // needed by RamUsageEstimator, and randomizedtesting runner to identify test methods.
- permission java.lang.RuntimePermission "accessDeclaredMembers";
- // needed by certain tests to capture sysout/syserr:
- permission java.lang.RuntimePermission "setIO";
- // needed by luke and randomized runner to catch failures from other threads:
- permission java.lang.RuntimePermission "setDefaultUncaughtExceptionHandler";
- // needed by tests e.g. shutting down executors:
- permission java.lang.RuntimePermission "modifyThread";
- // needed for tons of test hacks etc
- permission java.lang.RuntimePermission "getStackTrace";
- // needed for mock filesystems in tests
- permission java.lang.RuntimePermission "fileSystemProvider";
- // needed by cyberneko usage by benchmarks on J9
- permission java.lang.RuntimePermission "accessClassInPackage.org.apache.xerces.util";
-
- // Needed for DirectIODirectory to retrieve block size
- permission java.lang.RuntimePermission "getFileStoreAttributes";
-
- // TestLockFactoriesMultiJVM opens a random port on 127.0.0.1 (port 0 = ephemeral port range):
- permission java.net.SocketPermission "127.0.0.1:0", "accept,listen,resolve";
- // Replicator tests connect to ephemeral ports
- permission java.net.SocketPermission "127.0.0.1:1024-", "connect,resolve";
-
- // read access to all system properties:
- permission java.util.PropertyPermission "*", "read";
- // write access to only these:
- // locale randomization
- permission java.util.PropertyPermission "user.language", "write";
- // timezone randomization
- permission java.util.PropertyPermission "user.timezone", "write";
-
- // CMS randomization
- permission java.util.PropertyPermission "lucene.cms.override_core_count", "write";
-
- // used by nested tests? (e.g. TestLeaveFilesIfTestFails). TODO: look into this
- permission java.util.PropertyPermission "tests.runnested", "write";
-
- // allows LuceneTestCase#runWithRestrictedPermissions to execute with lower (or no) permission
- permission java.security.SecurityPermission "createAccessControlContext";
-
- // Hunspell regression and validation tests can read from external files
- // specified in system properties.
- permission java.io.FilePermission "${hunspell.repo.path}${/}-", "read";
- permission java.io.FilePermission "${hunspell.corpora}${/}-", "read";
- permission java.io.FilePermission "${hunspell.dictionaries}", "read";
- permission java.io.FilePermission "${hunspell.dictionaries}${/}-", "read";
-};
-
-// Permissions for jacoco code coverage
-grant {
- // permission to write the per-jvm code coverage output
- permission java.io.FilePermission "${user.dir}${/}jacoco.exec", "write";
- // needed by jacoco to dump coverage on shutdown
- permission java.lang.RuntimePermission "shutdownHooks";
- // needed by jacoco to instrument classes
- permission java.lang.RuntimePermission "defineClass";
- // needed by jacoco for God knows what.
- permission java.lang.RuntimePermission "createClassLoader";
-};
-
-// Grant all permissions to Gradle test runner classes.
-grant codeBase "file:${gradle.lib.dir}${/}-" {
- permission java.security.AllPermission;
-};
-
-grant codeBase "file:${gradle.worker.jar}" {
- permission java.security.AllPermission;
-};
-
-grant {
- // Allow reading gradle worker JAR.
- permission java.io.FilePermission "${gradle.worker.jar}", "read";
- // Allow reading from classpath JARs (resources).
- permission java.io.FilePermission "${gradle.user.home}${/}-", "read";
-};
-
-// Grant permissions to certain test-related JARs (https://github.com/apache/lucene/pull/13146)
-grant codeBase "file:${randomizedtesting.jar}" {
- permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
- permission java.lang.RuntimePermission "modifyThreadGroup";
-};
-grant codeBase "file:${junit.jar}" {
- permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
-};
-grant codeBase "file:${lucene.test.framework}${/}-" {
- permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
-};
diff --git a/gradle/validation/check-environment.gradle b/gradle/validation/check-environment.gradle
deleted file mode 100644
index 1eb00eee625..00000000000
--- a/gradle/validation/check-environment.gradle
+++ /dev/null
@@ -1,59 +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 checks that we're running the desired version of Gradle and
-// that the JVM is supported.
-
-import org.gradle.util.GradleVersion
-
-configure(rootProject) {
- ext {
- expectedGradleVersion = deps.versions.minGradle.get()
- hasJavaFlightRecorder = ModuleLayer.boot().findModule('jdk.jfr').map(this.class.module::canRead).orElse(false)
- }
-
- wrapper {
- distributionType = Wrapper.DistributionType.ALL
- gradleVersion = expectedGradleVersion
- }
-
- def currentJavaVersion = JavaVersion.current()
- def minJavaVersion = JavaVersion.toVersion(deps.versions.minJava.get())
- if (currentJavaVersion < minJavaVersion) {
- throw new GradleException("At least Java ${minJavaVersion} is required, you are running Java ${currentJavaVersion} "
- + "[${System.getProperty('java.vm.name')} ${System.getProperty('java.vm.version')}]")
- }
- if (Runtime.version().pre().isPresent()) {
- throw new GradleException("You are running Gradle with an EA version of Java, this is not supported! "
- + "To test Lucene compatibility with EA or prerelease versions, use the RUNTIME_JAVA_HOME environment variable. Detected Java version: "
- + "[${System.getProperty('java.vm.name')} ${System.getProperty('java.vm.version')}]")
- }
-
- // If we're regenerating the wrapper, skip the check.
- if (!gradle.startParameter.taskNames.contains("wrapper")) {
- def currentGradleVersion = GradleVersion.current()
- if (currentGradleVersion != GradleVersion.version(expectedGradleVersion)) {
- if (currentGradleVersion.baseVersion == GradleVersion.version(expectedGradleVersion).baseVersion) {
- logger.warn("Gradle ${expectedGradleVersion} is required but base version of this gradle matches, proceeding (" +
- "this gradle is ${currentGradleVersion})")
- } else {
- throw new GradleException("Gradle ${expectedGradleVersion} is required (hint: use the gradlew script): " +
- "this gradle is ${currentGradleVersion}")
- }
- }
- }
-}
diff --git a/gradle/validation/ecj-lint.gradle b/gradle/validation/ecj-lint.gradle
deleted file mode 100644
index b26c6c1b894..00000000000
--- a/gradle/validation/ecj-lint.gradle
+++ /dev/null
@@ -1,180 +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 'ecjLint' task.
-
-def resources = scriptResources(buildscript)
-
-allprojects {
- plugins.withType(JavaPlugin).configureEach {
-
- // Use Lucene's storage space for "drop" versions that are ahead
- // of official Maven publications.
- //
- // Drop versions are at:
- // https://www.eclipse.org/downloads/download.php?r=1&file=/eclipse/downloads/drops4/S-4.36M1-202504031800/ecj-${ecjVersion}.jar
- boolean useDropMirror = deps.versions.ecj.get() in ["4.36M1"]
- if (useDropMirror) {
- repositories {
- exclusiveContent {
- forRepository {
- ivy {
- url = 'https://s3.amazonaws.com/lucene-testdata/temp-repo/ecj/'
- patternLayout {
- artifact "[artifact]-[revision](.[ext])"
- m2compatible = true
- }
- metadataSources {
- it.artifact()
- }
- }
- }
- filter {
- includeGroup "org.eclipse.jdt"
- }
- }
- }
- }
-
- configurations {
- ecjDeps
- }
-
- dependencies {
- ecjDeps deps.ecj
- }
-
- def ecjConfiguration = configurations.ecjDeps
-
- // Create a [sourceSetName]EcjLint task for each source set
- // with a non-empty java.srcDirs. These tasks are then
- // attached to project's "ecjLint" task.
- def lintTasks = sourceSets.collect { SourceSet sourceSet ->
- def srcDirs = sourceSet.java.sourceDirectories
- .filter { dir -> dir.exists() }
-
- tasks.register(sourceSet.getTaskName("ecjLint", null), JavaExec, { JavaExec task ->
- // This dependency is on a configuration; technically it causes
- // all dependencies to be resolved before this task executes
- // (this includes scheduling tasks that compile the
- // sources from other projects for example).
- dependsOn sourceSet.compileClasspath
- dependsOn ecjConfiguration
-
- // The inputs are all source files from the sourceSet.
- inputs.files sourceSet.allSource.asFileTree
-
- // We create a task for all source sets but ignore those
- // that don't have any Java source directories.
- enabled = !srcDirs.isEmpty()
-
- // Ignore MR-JAR sourceSets.
- if (sourceSet.name ==~ /main\d+/) {
- enabled = false
- }
-
- classpath = ecjConfiguration
- mainClass = "org.eclipse.jdt.internal.compiler.batch.Main"
-
- // DOCS: https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-using_batch_compiler.htm
-
- // Don't emit any .class files.
- // Hack around "-d none" still emitting package-info.class
- // by running in a temporary directory.
- def tmpDst = getTemporaryDir()
- workingDir tmpDst
-
- args += [ "-d", "none" ]
-
- assert project.java.sourceCompatibility == project.java.targetCompatibility
-
- // Compilation environment.
- // we use -source/-target as it is significantly faster than --release
- args += [ "-source", project.java.sourceCompatibility ]
- args += [ "-target", project.java.targetCompatibility ]
- args += [ "-encoding", "UTF-8"]
- args += [ "-proc:none" ]
- args += [ "-nowarn" ]
- args += [ "-enableJavadoc" ]
- args += [ "-properties", file("${resources}/ecj.javadocs.prefs").absolutePath ]
-
- // We depend on modular paths.
- def modularPaths = sourceSet.modularPathsForEcj
- dependsOn modularPaths
-
- // Add modular dependencies and their transitive dependencies to module path.
- task.argumentProviders.add(modularPaths.compilationArguments)
-
- // Add classpath, if needed.
- task.argumentProviders.add((CommandLineArgumentProvider) {
- // Add classpath locations in a lazy provider (can't resolve the
- // configuration at evaluation time). Filter out non-existing entries
- // (output folders for non-existing input source dirs like resources).
- FileCollection cpath = modularPaths.compilationClasspath.filter { p -> p.exists() }
- if (!cpath.isEmpty()) {
- return ["-classpath", cpath.join(File.pathSeparator)]
- } else {
- return []
- }
- })
-
- // Place input files in an external file to dodge command line argument
- // limits. We could pass a directory but ecj seems to be buggy: when it
- // encounters a module-info.java file it no longer compiles other source files.
- def inputsFile = file("${tmpDst}/ecj-inputs.txt")
- task.argumentProviders.add((CommandLineArgumentProvider) {
- return ["@" + inputsFile.absolutePath]
- })
-
- doFirst {
- modularPaths.logCompilationPaths(logger)
-
- tmpDst.mkdirs()
-
- // escape filename accoring to ECJ's rules:
- // https://github.com/eclipse/aspectj.eclipse.jdt.core/blob/a05312e746b9bc2b48b4b039f6e7b5e061b5b393/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java#L1533-L1537
- // Basically surround all whitespace by quotes:
- def escapeFileName = { String s -> s.replaceAll(/ +/, /"$0"/) }
- inputsFile.setText(
- srcDirs.collectMany { dir ->
- project.fileTree(
- dir: dir,
- include: "**/*.java",
- // Exclude the benchmark class with dependencies on nekohtml, which causes module-classpath conflicts and breaks ecj.
- exclude: "**/DemoHTMLParser.java"
- ).files
- }
- // Try to sort all input files; a side-effect of this should be that module-info.java
- // is placed first on the list, which works around ECJ bug:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=569833
- .sort()
- .collect {file -> escapeFileName(file.absolutePath.toString())}.join("\n"), "UTF-8")
- }
- })
- }
-
- def ecjLint = tasks.register("ecjLint", {
- description "Lint Java sources using ECJ."
- group "Verification"
-
- dependsOn lintTasks
- })
-
- // Attach ecjLint to check.
- check.dependsOn ecjLint
- }
-}
diff --git a/gradle/validation/error-prone.gradle b/gradle/validation/error-prone.gradle
deleted file mode 100644
index 057e694d67e..00000000000
--- a/gradle/validation/error-prone.gradle
+++ /dev/null
@@ -1,615 +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 skipReason
-
-if (rootProject.usesAltJvm) {
- skipReason = "won't work with alternative java toolchain"
-}
-
-if (!propertyOrDefault("validation.errorprone", isCIBuild).asBoolean()) {
- skipReason = "skipped on builds not running inside CI environments, pass -Pvalidation.errorprone=true to enable"
-}
-
-if (skipReason) {
- configure(rootProject) {
- task errorProneSkipped() {
- doFirst {
- logger.warn("WARNING: errorprone disabled (${skipReason})")
- }
- }
- }
-}
-
-allprojects { prj ->
- plugins.withType(JavaPlugin) {
- // LUCENE-9650: Errorprone does not work when running as a plugin inside a forked Javac process.
- // Javac running inside Gradle works, because we have additional module system opens in place.
- if (skipReason) {
- tasks.withType(JavaCompile) { task -> task.dependsOn ":errorProneSkipped" }
-
- // Error prone plugin adds error prone to test classpath. We need to add it here too (manually) so that
- // versions.lock is consistent with or without error prone.
- configurations {
- errorprone
- }
- dependencies {
- errorprone deps.errorprone
- }
- configurations.annotationProcessor.extendsFrom(configurations.errorprone)
- } else {
- prj.apply plugin: deps.plugins.errorprone.get().pluginId
-
- dependencies {
- errorprone deps.errorprone
- }
-
- tasks.withType(JavaCompile) { task ->
- // Disable errorprone on the MR-JAR tasks
- if (task.name ==~ /compileMain\d+Java/) {
- options.errorprone.enabled = false
- return
- }
-
- // Exclude certain files (generated ones, mostly).
- switch (project.path) {
- case ":lucene:core":
- options.errorprone.excludedPaths.set(".*/StandardTokenizerImpl.java")
- break
-
- case ":lucene:analysis:common":
- options.errorprone.excludedPaths.set("" +
- ".*/HTMLStripCharFilter.java|" +
- ".*/UAX29URLEmailTokenizerImpl.java")
- break
-
- case ":lucene:test-framework":
- options.errorprone.excludedPaths.set("" +
- ".*/EmojiTokenizationTestUnicode_11_0.java|" +
- ".*/WordBreakTestUnicode_9_0_0.java")
- break
-
- case ":lucene:expressions":
- break
-
- case ":lucene:queryparser":
- options.errorprone.excludedPaths.set("" +
- ".*/classic/ParseException.java|" +
- ".*/classic/QueryParser.java|" +
- ".*/classic/QueryParserConstants.java|" +
- ".*/classic/QueryParserTokenManager.java|" +
- ".*/classic/Token.java|" +
- ".*/classic/TokenMgrError.java|" +
- ".*/standard/parser/ParseException.java|" +
- ".*/standard/parser/StandardSyntaxParser.java|" +
- ".*/standard/parser/StandardSyntaxParserConstants.java|" +
- ".*/standard/parser/StandardSyntaxParserTokenManager.java|" +
- ".*/standard/parser/Token.java|" +
- ".*/standard/parser/TokenMgrError.java|" +
- ".*/surround/parser/ParseException.java|" +
- ".*/surround/parser/QueryParser.java|" +
- ".*/surround/parser/QueryParserConstants.java|" +
- ".*/surround/parser/QueryParserTokenManager.java|" +
- ".*/surround/parser/Token.java|" +
- ".*/surround/parser/TokenMgrError.java")
- break
- }
-
- task.dependsOn ":checkJdkInternalsExportedToGradle"
-
- options.errorprone.disableWarningsInGeneratedCode = true
- options.errorprone.errorproneArgs = [
- '-XepDisableAllChecks', // only enable specific checks
- '-XepAllErrorsAsWarnings', // warnings still fail build by default, but allows usage of -Pjavac.failOnWarnings=false
-
- // List of enabled/disabled checks
- // Please keep this synced with https://errorprone.info/bugpatterns when upgrading!
- // Do *NOT* enable checks based on their name or description. Read the source code and make sure they are useful!
- // Most error-prone checks are not useful for non-google software.
-
- // On by Default : ERROR
-
- // '-Xep:AddNullMarkedToPackageInfo:OFF', // we don't use jspecify
- // '-Xep:AlwaysThrows:OFF', // we don't use google collections
- // '-Xep:AndroidInjectionBeforeSuper:OFF', // we don't use android
- '-Xep:ArrayEquals:ERROR',
- '-Xep:ArrayFillIncompatibleType:ERROR',
- '-Xep:ArrayHashCode:ERROR',
- '-Xep:ArrayToString:ERROR',
- // '-Xep:ArraysAsListPrimitiveArray:OFF', // we don't use guava
- // '-Xep:AssignmentExpression:OFF', // TODO: there are problems
- // '-Xep:AsyncCallableReturnsNull:OFF', // we don't use guava
- // '-Xep:AsyncFunctionReturnsNull:OFF', // we don't use guava
- // '-Xep:AutoValueBuilderDefaultsInConstructor:OFF', // we don't use autovalue
- // '-Xep:AutoValueConstructorOrderChecker:OFF', // we don't use autovalue
- '-Xep:BadAnnotationImplementation:ERROR',
- '-Xep:BadShiftAmount:ERROR',
- '-Xep:BanClassLoader:ERROR',
- // '-Xep:BanJNDI:OFF', // implemented with forbidden APIs instead
- // '-Xep:BoxedPrimitiveEquality:OFF', // TODO: there are problems
- // '-Xep:BundleDeserializationCast:OFF', // we don't use android
- '-Xep:ChainingConstructorIgnoresParameter:ERROR',
- // '-Xep:CheckNotNullMultipleTimes:OFF', // we don't use guava
- // '-Xep:CheckReturnValue:OFF', // we don't use these annotations
- '-Xep:CollectionToArraySafeParameter:ERROR',
- // '-Xep:ComparableType:OFF',
- '-Xep:ComparingThisWithNull:ERROR',
- '-Xep:ComparisonOutOfRange:ERROR',
- // '-Xep:CompatibleWithAnnotationMisuse:OFF', // we don't use this annotation
- // '-Xep:CompileTimeConstant:OFF', // we don't use this annotation
- '-Xep:ComputeIfAbsentAmbiguousReference:ERROR',
- '-Xep:ConditionalExpressionNumericPromotion:ERROR',
- '-Xep:ConstantOverflow:ERROR',
- // '-Xep:DaggerProvidesNull:OFF', // we don't use dagger
- '-Xep:DangerousLiteralNull:ERROR',
- '-Xep:DeadException:ERROR',
- '-Xep:DeadThread:ERROR',
- '-Xep:DereferenceWithNullBranch:ERROR',
- '-Xep:DiscardedPostfixExpression:ERROR',
- // '-Xep:DoNotCall:OFF', // we don't use this annotation
- // '-Xep:DoNotMock:OFF', // we don't use mocking libraries
- // '-Xep:DoubleBraceInitialization:OFF', // we don't use guava
- '-Xep:DuplicateBranches:ERROR',
- '-Xep:DuplicateMapKeys:ERROR',
- // '-Xep:DurationFrom:OFF', // we don't use Duration.from()
- // '-Xep:DurationGetTemporalUnit:OFF', // we don't use Duration.get()
- // '-Xep:DurationTemporalUnit:OFF', // we don't use Duration.of() etc
- // '-Xep:DurationToLongTimeUnit:OFF', // we don't use TimeUnit.convert Duration, etc
- // '-Xep:EmptyTopLevelDeclaration:OFF', // noisy
- '-Xep:EqualsHashCode:ERROR',
- '-Xep:EqualsNaN:ERROR',
- '-Xep:EqualsNull:ERROR',
- '-Xep:EqualsReference:ERROR',
- '-Xep:EqualsWrongThing:ERROR',
- // '-Xep:FloggerFormatString:OFF', // we don't use flogger
- // '-Xep:FloggerLogVarargs:OFF', // we don't use flogger
- // '-Xep:FloggerSplitLogStatement:OFF', // we don't use flogger
- // '-Xep:ForOverride:OFF', // we don't use this annotation
- // '-Xep:FormatString:OFF',
- // '-Xep:FormatStringAnnotation:OFF', // we don't use this annotation
- // '-Xep:FromTemporalAccessor:OFF', // we don't use .from(LocalDate) etc
- '-Xep:FunctionalInterfaceMethodChanged:ERROR',
- // '-Xep:FuturesGetCheckedIllegalExceptionType:OFF', // we don't use guava
- // '-Xep:FuzzyEqualsShouldNotBeUsedInEqualsMethod:OFF', // we don't use guava
- '-Xep:GetClassOnAnnotation:ERROR',
- '-Xep:GetClassOnClass:ERROR',
- // '-Xep:GuardedBy:OFF', // we don't use this annotation
- // '-Xep:GuiceAssistedInjectScoping:OFF', // we don't use guice
- // '-Xep:GuiceAssistedParameters:OFF', // we don't use guice
- // '-Xep:GuiceInjectOnFinalField:OFF', // we don't use guice
- '-Xep:HashtableContains:ERROR',
- // '-Xep:IdentityBinaryExpression:OFF',
- '-Xep:IdentityHashMapBoxing:ERROR',
- // '-Xep:IgnoredPureGetter:OFF', // we don't use these annotations
- // '-Xep:Immutable:OFF', // we don't use this annotation
- // '-Xep:ImpossibleNullComparison:OFF', // we don't use protobuf
- '-Xep:Incomparable:ERROR',
- // '-Xep:IncompatibleArgumentType:OFF', // we don't use this annotation
- // '-Xep:IncompatibleModifiers:OFF', // we don't use this annotation
- '-Xep:IndexOfChar:ERROR',
- '-Xep:InexactVarargsConditional:ERROR',
- // '-Xep:InfiniteRecursion:OFF',
- // '-Xep:InjectMoreThanOneScopeAnnotationOnClass:OFF', // we don't use this annotation
- // '-Xep:InjectOnMemberAndConstructor:OFF', // we don't use this annotation
- // '-Xep:InlineMeValidator:OFF', // we don't use this annotation
- // '-Xep:InstantTemporalUnit:OFF', // we don't use Instant apis with strange temporal units
- '-Xep:IntFloatConversion:ERROR',
- // '-Xep:IntLiteralCast:OFF', // TODO: there are problems
- // '-Xep:InvalidJavaTimeConstant:OFF', // we don't use impacted java.time classes (Month, etc)
- // '-Xep:InvalidPatternSyntax:OFF',
- '-Xep:InvalidSnippet:ERROR',
- // '-Xep:InvalidTimeZoneID:OFF', // we don't use getTimeZone with constant IDs except UTC/GMT
- // '-Xep:InvalidZoneId:OFF', // we don't use ZoneId.of
- '-Xep:IsInstanceIncompatibleType:ERROR',
- '-Xep:IsInstanceOfClass:ERROR',
- // '-Xep:IsLoggableTagLength:OFF', // we don't use android
- // '-Xep:JUnit3TestNotRun:OFF', // we don't use junit3
- '-Xep:JUnit4ClassAnnotationNonStatic:ERROR',
- '-Xep:JUnit4EmptyMethods:ERROR',
- // '-Xep:JUnit4SetUpNotRun:OFF', // LuceneTestCase takes care
- // '-Xep:JUnit4TearDownNotRun:OFF', // LuceneTestCase takes care
- // '-Xep:JUnit4TestNotRun:OFF', // noisy
- '-Xep:JUnit4TestsNotRunWithinEnclosed:ERROR',
- '-Xep:JUnitAssertSameCheck:ERROR',
- '-Xep:JUnitParameterMethodNotFound:ERROR',
- // '-Xep:JavaxInjectOnAbstractMethod:OFF', // we don't this annotation
- // '-Xep:JodaToSelf:OFF', // we don't use joda-time
- // '-Xep:LenientFormatStringValidation:OFF' // we don't use these google libraries
- // '-Xep:LiteByteStringUtf8:OFF', // we don't use protobuf
- // '-Xep:LocalDateTemporalAmount:OFF', // we don't use LocalDate math
- '-Xep:LockOnBoxedPrimitive:ERROR',
- '-Xep:LoopConditionChecker:ERROR',
- '-Xep:LossyPrimitiveCompare:ERROR',
- '-Xep:MathRoundIntLong:ERROR',
- // '-Xep:MislabeledAndroidString:OFF', // we don't use android
- '-Xep:MisleadingEmptyVarargs:ERROR',
- '-Xep:MisleadingEscapedSpace:ERROR',
- // '-Xep:MissingRuntimeRetention:OFF', // we don't use this annotation
- // '-Xep:MisplacedScopeAnnotations:OFF', // we don't use this annotation
- // '-Xep:MissingSuperCall:OFF', // we don't use this annotation
- // '-Xep:MissingTestCall:OFF', // we don't use guava
- // '-Xep:MisusedDayOfYear:OFF', // we don't use date patterns
- // '-Xep:MisusedWeekYear:OFF', // we don't use date patterns
- // '-Xep:MixedDescriptors:OFF', // we don't use protobuf
- // '-Xep:MockIllegalThrows:OFF', // we don't use mockito
- // '-Xep:MockitoUsage:OFF', // we don't use mockito
- '-Xep:ModifyingCollectionWithItself:ERROR',
- // '-Xep:MoreThanOneInjectableConstructor:OFF', // we don't use this annotation
- // '-Xep:MustBeClosedChecker:OFF', // we don't use this annotation
- '-Xep:NCopiesOfChar:ERROR',
- // '-Xep:NegativeBoolean:OFF', // TODO: there are problems
- // '-Xep:NoCanIgnoreReturnValueOnClasses:OFF', // we don't use this annotation
- '-Xep:NonCanonicalStaticImport:ERROR',
- // '-Xep:NonFinalCompileTimeConstant:OFF', // we don't use this annotation
- '-Xep:NonRuntimeAnnotation:ERROR',
- // '-Xep:NullArgumentForNonNullParameter:OFF', // we don't use this annotation
- '-Xep:NullTernary:ERROR',
- // '-Xep:NullableOnContainingClass:OFF', // we don't use this annotation
- '-Xep:OptionalEquality:ERROR',
- '-Xep:OptionalMapUnusedValue:ERROR',
- '-Xep:OptionalOfRedundantMethod:ERROR',
- // '-Xep:OverlappingQualifierAndScopeAnnotation:OFF', // we don't use this annotation
- // '-Xep:OverridesJavaxInjectableMethod:OFF', // we don't use this annotation
- '-Xep:PackageInfo:ERROR',
- '-Xep:ParametersButNotParameterized:ERROR',
- // '-Xep:ParcelableCreator:OFF', // we don't use android
- // '-Xep:PeriodFrom:OFF', // we don't use Period
- // '-Xep:PeriodGetTemporalUnit:OFF', // we don't use Period
- // '-Xep:PeriodTimeMath:OFF', // we don't use Period
- // '-Xep:PreconditionsInvalidPlaceholder:OFF', // we don't use guava
- // '-Xep:PreconditionsExpensiveString:OFF', // we don't use guava
- // '-Xep:PrivateSecurityContractProtoAccess:OFF', // we don't use protobuf
- // '-Xep:ProtoBuilderReturnValueIgnored:OFF', // we don't use protobuf
- // '-Xep:ProtoFieldNullComparison:OFF', // we don't use protobuf
- // '-Xep:ProtoStringFieldReferenceEquality:OFF', // we don't use protobuf
- // '-Xep:ProtoTruthMixedDescriptors:OFF', // we don't use protobuf
- // '-Xep:ProtocolBufferOrdinal:OFF', // we don't use protobuf
- // '-Xep:ProvidesMethodOutsideOfModule:OFF', // we don't use guice
- '-Xep:RandomCast:ERROR',
- '-Xep:RandomModInteger:ERROR',
- // '-Xep:RectIntersectReturnValueIgnored:OFF', // we don't use android
- // '-Xep:RequiredModifiers:OFF', // we don't use this annotation
- // '-Xep:RestrictedApiChecker:OFF', // we don't use this annotation
- // '-Xep:ReturnValueIgnored:OFF', // noisy
- '-Xep:RuleNotRun:ERROR',
- '-Xep:SelfAssertion:ERROR',
- '-Xep:SelfAssignment:ERROR',
- '-Xep:SelfComparison:ERROR',
- '-Xep:SelfEquals:ERROR',
- '-Xep:SelfSet:ERROR',
- // '-Xep:SetUnrecognized:OFF', // we don't use protobuf
- // '-Xep:ShouldHaveEvenArgs:OFF', // we don't use truth
- '-Xep:SizeGreaterThanOrEqualsZero:ERROR',
- '-Xep:StreamToString:ERROR',
- '-Xep:StringBuilderInitWithChar:ERROR',
- // '-Xep:StringConcatToTextBlock:OFF', // TODO: there are problems
- '-Xep:SubstringOfZero:ERROR',
- '-Xep:SuppressWarningsDeprecated:ERROR',
- // '-Xep:TemporalAccessorGetChronoField:OFF', // we don't use TemporalAccessor.get
- // '-Xep:TestParametersNotInitialized:OFF', // we don't use this annotation
- // '-Xep:TheoryButNoTheories:OFF', // we don't use junit theory apis/runner
- // '-Xep:ThrowIfUncheckedKnownChecked:OFF', // we don't use this annotation
- // '-Xep:ThrowNull:OFF', // noisy (LuceneTestCase)
- '-Xep:TimeInStaticInitializer:ERROR',
- // '-Xep:TreeToString:OFF', // we don't use javac API
- // '-Xep:TryFailThrowable:OFF',
- '-Xep:TypeParameterQualifier:ERROR',
- '-Xep:UnicodeDirectionalityCharacters:ERROR',
- '-Xep:UnicodeInCode:ERROR',
- '-Xep:UnnecessaryCheckNotNull:ERROR',
- // '-Xep:UnnecessaryCopy:OFF', // we don't use google collections
- '-Xep:UnnecessaryTypeArgument:ERROR',
- '-Xep:UnsafeWildcard:ERROR',
- '-Xep:UnusedAnonymousClass:ERROR',
- '-Xep:UnusedCollectionModifiedInPlace:ERROR',
- '-Xep:VarTypeName:ERROR',
- // '-Xep:WrongOneof:OFF', // we don't use protobuf
- '-Xep:XorPower:ERROR',
- // '-Xep:ZoneIdOfZ:OFF', // we don't use ZoneId.of
-
- // On by Default : WARNING
-
- // '-Xep:ASTHelpersSuggestions:OFF', // we don't use ASTHelpers
- // '-Xep:AlmostJavadoc:OFF', // noisy (e.g. commented-out code misinterpreted as javadocs)
- // '-Xep:AlreadyChecked:OFF', // TODO: there are problems
- // '-Xep:AmbiguousMethodReference:OFF',
- // '-Xep:AnnotateFormatMethod:OFF', // we don't use this annotation
- // '-Xep:ArgumentSelectionDefectChecker:OFF', // noisy
- // '-Xep:ArrayAsKeyOfSetOrMap:OFF', // TODO: there are problems
- // '-Xep:ArrayRecordComponent:OFF', // TODO: there are problems
- '-Xep:AssertEqualsArgumentOrderChecker:WARN',
- '-Xep:AssertThrowsMultipleStatements:WARN',
- // '-Xep:AssertionFailureIgnored:OFF', // TODO: there are problems
- // '-Xep:AssistedInjectAndInjectOnSameConstructor:OFF', // we don't use this annotation
- '-Xep:AttemptedNegativeZero:WARN',
- // '-Xep:AutoValueBoxedValues:OFF', // we don't use autovalue
- // '-Xep:AutoValueFinalMethods:OFF', // we don't use autovalue
- // '-Xep:AutoValueImmutableFields:OFF', // we don't use autovalue
- // '-Xep:AutoValueSubclassLeaked:OFF', // we don't use autovalue
- '-Xep:BadComparable:WARN',
- // '-Xep:BadImport:OFF', // TODO: there are problems
- // '-Xep:BadInstanceof:OFF', // TODO: there are problems
- '-Xep:BareDotMetacharacter:WARN',
- // '-Xep:BigDecimalEquals:OFF', // BigDecimal barely used, can use forbidden-apis for this
- // '-Xep:BigDecimalLiteralDouble:OFF', // BigDecimal barely used, can use forbidden-apis for this
- // '-Xep:BoxedPrimitiveConstructor:OFF', // we have forbiddenapis for that
- // '-Xep:BugPatternNaming:OFF', // we don't use this annotation
- // '-Xep:ByteBufferBackingArray:OFF',
- // '-Xep:CacheLoaderNull:OFF', // we don't use guava
- // '-Xep:CanonicalDuration:OFF', // barely use Duration.of (one test), just a style thing
- // '-Xep:CatchAndPrintStackTrace:OFF', // noisy
- // '-Xep:CatchFail:OFF', // TODO: there are problems
- // '-Xep:ChainedAssertionLosesContext:OFF', // we don't use truth
- // '-Xep:CharacterGetNumericValue:OFF', // noisy
- // '-Xep:ClassCanBeStatic:OFF', // noisy
- // '-Xep:ClassInitializationDeadlock:OFF', // TODO: there are problems
- '-Xep:ClassNewInstance:WARN',
- // '-Xep:CloseableProvides:OFF', // we don't use this annotation
- '-Xep:ClosingStandardOutputStreams:WARN',
- // '-Xep:CollectionUndefinedEquality:OFF', // TODO: there are problems
- '-Xep:CollectorShouldNotUseState:WARN',
- '-Xep:ComparableAndComparator:WARN',
- '-Xep:CompareToZero:WARN',
- // '-Xep:ComplexBooleanConstant:OFF', // TODO: there are problems
- // '-Xep:DateChecker:OFF', // we don't use these Date setters/ctors
- // '-Xep:DateFormatConstant:OFF', // we don't use Date setters
- // '-Xep:DefaultCharset:OFF', // we have forbiddenapis for that
- // '-Xep:DefaultLocale:OFF', // we have forbiddenapis for that
- // '-Xep:DefaultPackage:OFF',
- '-Xep:DeprecatedVariable:WARN',
- '-Xep:DeeplyNested:WARN',
- // '-Xep:DirectInvocationOnMock:OFF', // we don't use mocking libraries
- // '-Xep:DistinctVarargsChecker:OFF', // we don't use google collections
- // '-Xep:DoNotCallSuggester:OFF', // we don't use this annotation
- // '-Xep:DoNotClaimAnnotations:OFF', // we don't use annotation processors
- // '-Xep:DoNotMockAutoValue:OFF', // we don't use autovalue
- // '-Xep:DoubleCheckedLocking:OFF', // TODO: there are problems
- '-Xep:DuplicateDateFormatField:WARN',
- '-Xep:EmptyBlockTag:WARN',
- // '-Xep:EmptyCatch:OFF', // ECJ takes care
- // '-Xep:EmptySetMultibindingContributions:OFF', // we don't use this annotation
- // '-Xep:EnumOrdinal:OFF', // noisy
- // '-Xep:EqualsGetClass:OFF', // noisy
- // '-Xep:EqualsIncompatibleType:OFF',
- // '-Xep:EqualsUnsafeCast:OFF', // noisy
- '-Xep:EqualsUsingHashCode:WARN',
- '-Xep:ErroneousBitwiseExpression:WARN',
- '-Xep:ErroneousThreadPoolConstructorChecker:WARN',
- // '-Xep:EscapedEntity:OFF',
- // '-Xep:ExtendingJUnitAssert:OFF', // noisy
- // '-Xep:ExtendsObject:OFF', // TODO: there are problems
- // '-Xep:FallThrough:OFF', // TODO: there are problems
- '-Xep:Finalize:WARN', // catches actual finalizers that don't call super
- // '-Xep:Finally:OFF', // TODO: there are problems
- '-Xep:FloatCast:WARN',
- '-Xep:FloatingPointAssertionWithinEpsilon:WARN',
- // '-Xep:FloatingPointLiteralPrecision:OFF', // TODO: there are problems
- // '-Xep:FloggerArgumentToString:OFF', // we don't use flogger
- // '-Xep:FloggerStringConcatenation:OFF', // we don't use flogger
- // '-Xep:FragmentInjection:OFF', // we don't use android
- // '-Xep:FragmentNotInstantiable:OFF', // we don't use android
- // '-Xep:FutureReturnValueIgnored:OFF', // TODO: there are problems
- // '-Xep:FutureTransformAsync:OFF', // we don't use these google libraries
- '-Xep:GetClassOnEnum:WARN',
- // '-Xep:GuiceNestedCombine:OFF', // we don't use guice
- // '-Xep:HidingField:OFF', // noisy
- '-Xep:ICCProfileGetInstance:WARN',
- // '-Xep:IdentityHashMapUsage:OFF', // noisy
- // '-Xep:ImmutableAnnotationChecker:OFF', // we don't use this annotation
- // '-Xep:ImmutableEnumChecker:OFF', // noisy
- // '-Xep:InconsistentCapitalization:OFF', // TODO: there are problems
- // '-Xep:InconsistentHashCode:OFF', // noisy
- // '-Xep:IgnoredPureGetter:OFF', // we don't use these google libraries
- '-Xep:IncorrectMainMethod:WARN',
- '-Xep:IncrementInForLoopAndHeader:WARN',
- '-Xep:InheritDoc:WARN',
- // '-Xep:InjectOnBugCheckers:OFF', // we don't use this annotation
- // '-Xep:InjectInvalidTargetingOnScopingAnnotation:OFF', // we don't use this annotation
- // '-Xep:InjectOnConstructorOfAbstractClass:OFF', // we don't use this annotation
- // '-Xep:InjectScopeAnnotationOnInterfaceOrAbstractClass:OFF', // we don't use this annotation
- // '-Xep:InjectedConstructorAnnotations:OFF', // we don't use this annotation
- // '-Xep:InlineFormatString:OFF', // noisy
- // '-Xep:InlineMeInliner:OFF', // we don't use this annotation
- // '-Xep:InlineMeSuggester:OFF', // we don't use this annotation
- // '-Xep:InlineTrivialConstant:OFF', // stylistic
- // '-Xep:InputStreamSlowMultibyteRead:OFF',
- '-Xep:InstanceOfAndCastMatchWrongType:WARN',
- // '-Xep:IntLongMath:OFF', // noisy
- // '-Xep:InvalidBlockTag:OFF', // noisy (e.g. lucene.experimental)
- // '-Xep:InvalidInlineTag:OFF', // TODO: there are problems
- '-Xep:InvalidLink:WARN',
- // '-Xep:InvalidParam:OFF', // TODO: there are problems
- '-Xep:InvalidThrows:WARN',
- '-Xep:InvalidThrowsLink:WARN',
- '-Xep:IterableAndIterator:WARN',
- // '-Xep:JUnit3FloatingPointComparisonWithoutDelta:OFF', // we don't use junit3
- // '-Xep:JUnit4ClassUsedInJUnit3:OFF', // we don't use junit3
- // '-Xep:JUnitAmbiguousTestClass:OFF', // we don't use junit3
- // '-Xep:JavaDurationGetSecondsGetNano:OFF', // we don't use these Duration methods
- // '-Xep:JavaDurationGetSecondsToToSeconds:OFF', // we don't use these Duration methods
- // '-Xep:JavaDurationWithNanos:OFF', // we don't use these Duration methods
- // '-Xep:JavaDurationWithSeconds:OFF', // we don't use these Duration methods
- // '-Xep:JavaInstantGetSecondsGetNano:OFF', // we don't use these Instant methods
- // '-Xep:JavaLangClash:OFF', // TODO: there are problems
- // '-Xep:JavaLocalDateTimeGetNano:OFF', // we don't use LocalDateTime
- // '-Xep:JavaLocalTimeGetNano:OFF', // we don't use LocalTime
- // '-Xep:JavaPeriodGetDays:OFF', // we don't use Period
- // '-Xep:JavaTimeDefaultTimeZone:OFF', // forbidden-apis checks this
- // '-Xep:JavaUtilDate:OFF', // noisy
- // '-Xep:JavaxInjectOnFinalField:OFF', // we don't use this annotation
- // '-Xep:JdkObsolete:OFF', // noisy
- // '-Xep:JodaConstructors:OFF', // we don't use joda-time
- // '-Xep:JodaDateTimeConstants:OFF', // we don't use joda-time
- // '-Xep:JodaDurationWithMillis:OFF', // we don't use joda-time
- // '-Xep:JodaInstantWithMillis:OFF', // we don't use joda-time
- // '-Xep:JodaNewPeriod:OFF', // we don't use joda-time
- // '-Xep:JodaPlusMinusLong:OFF', // we don't use joda-time
- // '-Xep:JodaTimeConverterManager:OFF', // we don't use joda-time
- // '-Xep:JodaWithDurationAddedLong:OFF', // we don't use joda-time
- '-Xep:JUnitIncompatibleType:WARN',
- // '-Xep:LabelledBreakTarget:OFF', // stylistic
- // '-Xep:LiteEnumValueOf:OFF', // we don't use protobuf
- // '-Xep:LiteProtoToString:OFF', // we don't use protobuf
- // '-Xep:LockNotBeforeTry:OFF', // TODO: there are problems
- // '-Xep:LockOnNonEnclosingClassLiteral:OFF', // TODO: there are problems
- '-Xep:LogicalAssignment:WARN',
- '-Xep:LongDoubleConversion:WARN',
- '-Xep:LongFloatConversion:WARN',
- '-Xep:LoopOverCharArray:WARN',
- '-Xep:MalformedInlineTag:WARN',
- // '-Xep:MathAbsoluteNegative:OFF', // TODO: there are problems
- // '-Xep:MemoizeConstantVisitorStateLookups:OFF', // we don't use this class
- // '-Xep:MisformattedTestData:OFF', // stylistic
- // '-Xep:MissingCasesInEnumSwitch:OFF', // redundant with ECJ incompleteEnumSwitch/missingEnumCaseDespiteDefault
- // '-Xep:MissingFail:OFF', // TODO: there are problems
- '-Xep:MissingImplementsComparable:WARN',
- // '-Xep:MissingOverride:OFF', // ECJ takes care of this
- // '-Xep:MissingRefasterAnnotation:OFF', // we don't use this annotation
- // '-Xep:MissingSummary:OFF', // TODO: there are problems
- // '-Xep:MixedMutabilityReturnType:OFF', // noisy
- // '-Xep:MockitoDoSetup:OFF', // we don't use mocking libraries
- // '-Xep:MockNotUsedInProduction:OFF', // we don't use mocking libraries
- // '-Xep:ModifiedButNotUsed:OFF', // TODO: there are problems
- '-Xep:ModifyCollectionInEnhancedForLoop:WARN',
- '-Xep:ModifySourceCollectionInStream:WARN',
- '-Xep:MultimapKeys:WARN',
- // '-Xep:MultipleNullnessAnnotations:OFF', // we don't use these annotations
- '-Xep:MultipleParallelOrSequentialCalls:WARN',
- '-Xep:MultipleUnaryOperatorsInMethodCall:WARN',
- // '-Xep:MutableGuiceModule:OFF', // we don't use guice
- // '-Xep:MutablePublicArray:OFF', // TODO: there are problems
- '-Xep:NamedLikeContextualKeyword:WARN',
- '-Xep:NarrowCalculation:WARN',
- // '-Xep:NarrowingCompoundAssignment:OFF', // noisy
- '-Xep:NegativeCharLiteral:WARN',
- '-Xep:NestedInstanceOfConditions:WARN',
- // '-Xep:NewFileSystem:OFF', // we don't create new filesystems
- // '-Xep:NonApiType:OFF', // noisy
- // '-Xep:NonAtomicVolatileUpdate:OFF', // TODO: there are problems
- // '-Xep:NonCanonicalType:OFF', // noisy
- '-Xep:NonFinalStaticField:WARN',
- '-Xep:NonOverridingEquals:WARN',
- '-Xep:NotJavadoc:WARN',
- '-Xep:NullOptional:WARN',
- // '-Xep:NullableConstructor:OFF', // we don't use this annotation
- '-Xep:NullableOptional:WARN',
- // '-Xep:NullablePrimitive:OFF', // we don't use this annotation
- // '-Xep:NullablePrimitiveArray:OFF', // we don't use this annotation
- // '-Xep:NullableTypeParameter:OFF', // we don't use this annotation
- // '-Xep:NullableVoid:OFF', // we don't use this annotation
- // '-Xep:NullableWildcard:OFF', // we don't use this annotation
- '-Xep:ObjectEqualsForPrimitives:WARN',
- // '-Xep:ObjectToString:OFF', // TODO: there are problems
- // '-Xep:ObjectsHashCodePrimitive:OFF', // TODO: there are problems
- // '-Xep:OperatorPrecedence:OFF', // noisy
- '-Xep:OptionalMapToOptional:WARN',
- '-Xep:OptionalNotPresent:WARN',
- '-Xep:OrphanedFormatString:WARN',
- // '-Xep:OutlineNone:OFF', // we don't use gwt
- '-Xep:OverrideThrowableToString:WARN',
- '-Xep:Overrides:WARN',
- // '-Xep:OverridesGuiceInjectableMethod:OFF', // we don't use guice
- '-Xep:OverridingMethodInconsistentArgumentNamesChecker:WARN',
- // '-Xep:PatternMatchingInstanceof:OFF', // there are problems and check seems not great
- // '-Xep:ParameterName:OFF', // we don't pass parameters with comments in this way
- // '-Xep:PreconditionsCheckNotNullRepeated:OFF', // we don't use guava
- '-Xep:PrimitiveAtomicReference:WARN',
- // '-Xep:ProtectedMembersInFinalClass:OFF', // we don't use protobuf
- // '-Xep:ProtoDurationGetSecondsGetNano:OFF', // we don't use protobuf
- // '-Xep:ProtoRedundantSet:OFF', // we don't use protobuf
- // '-Xep:ProtoTimestampGetSecondsGetNano:OFF', // we don't use protobuf
- // '-Xep:QualifierOrScopeOnInjectMethod:OFF', // we don't use this annotation
- '-Xep:ReachabilityFenceUsage:WARN',
- // '-Xep:RedundantControlFlow:OFF', // stylistic
- // '-Xep:RedundantSetterCall:OFF', // we don't use protobuf
- // '-Xep:ReferenceEquality:OFF', // noisy
- '-Xep:RethrowReflectiveOperationExceptionAsLinkageError:WARN',
- // '-Xep:ReturnAtTheEndOfVoidFunction:OFF', // stylistic
- '-Xep:ReturnFromVoid:WARN',
- // '-Xep:RobolectricShadowDirectlyOn:OFF', // we don't use robolectric
- // '-Xep:RxReturnValueIgnored:OFF', // we don't use rxjava
- // '-Xep:SameNameButDifferent:OFF', // TODO: there are problems
- // '-Xep:SelfAlwaysReturnsThis:OFF', // we don't use self() methods, this isn't python.
- // '-Xep:ShortCircuitBoolean:OFF', // TODO: there are problems
- // '-Xep:StatementSwitchToExpressionSwitch:OFF', // TODO: there are problems
- // '-Xep:StaticAssignmentInConstructor:OFF',
- // '-Xep:StaticAssignmentOfThrowable:OFF', // noisy
- // '-Xep:StaticGuardedByInstance:OFF',
- // '-Xep:StaticMockMember:OFF', // we don't use mock libraries
- // '-Xep:StreamResourceLeak:OFF', // TODO: there are problems
- '-Xep:StreamToIterable:WARN',
- // '-Xep:StringCaseLocaleUsage:OFF', // noisy, can use forbidden-apis for this
- '-Xep:StringCharset:WARN',
- '-Xep:StringFormatWithLiteral:WARN',
- // '-Xep:StringSplitter:OFF', // noisy, can use forbidden-apis for this
- '-Xep:SystemConsoleNull:WARN',
- '-Xep:SunApi:WARN',
- '-Xep:SuperCallToObjectMethod:WARN',
- // '-Xep:SwigMemoryLeak:OFF', // we don't use swig
- // '-Xep:SynchronizeOnNonFinalField:OFF', // noisy
- // '-Xep:ThreadJoinLoop:OFF',
- // '-Xep:ThreadLocalUsage:OFF', // noisy
- // '-Xep:ThreadPriorityCheck:OFF', // noisy, forbidden APIs can do this
- // '-Xep:ThrowIfUncheckedKnownUnchecked:OFF', // we don't use these google libraries
- '-Xep:ThreeLetterTimeZoneID:WARN',
- '-Xep:TimeUnitConversionChecker:WARN',
- // '-Xep:ToStringReturnsNull:OFF', // TODO: there are problems
- // '-Xep:TruthAssertExpected:OFF', // we don't use truth
- // '-Xep:TruthConstantAsserts:OFF', // we don't use truth
- // '-Xep:TruthContainsExactlyElementsInUsage:OFF', // we don't use truth
- // '-Xep:TruthGetOrDefault:OFF', // we don't use truth
- // '-Xep:TruthIncompatibleType:OFF', // we don't use truth
- // '-Xep:TypeEquals:OFF', // we don't use this internal javac api
- '-Xep:TypeNameShadowing:WARN',
- // '-Xep:TypeParameterShadowing:OFF',
- // '-Xep:TypeParameterUnusedInFormals:OFF',
- '-Xep:URLEqualsHashCode:WARN',
- // '-Xep:UndefinedEquals:OFF', // TODO: there are problems
- // '-Xep:UnescapedEntity:OFF', // TODO: there are problems
- // '-Xep:UnicodeEscape:OFF', // noisy
- '-Xep:UnnecessaryAsync:WARN',
- // '-Xep:UnnecessaryAssignment:OFF', // we don't use these annotations
- '-Xep:UnnecessaryBreakInSwitch:WARN',
- // '-Xep:UnnecessaryLambda:OFF', // TODO: there are problems
- // '-Xep:UnnecessaryLongToIntConversion:OFF', // TODO: there are problems
- // '-Xep:UnnecessaryMethodInvocationMatcher:OFF', // we don't use spring
- '-Xep:UnnecessaryMethodReference:WARN',
- // '-Xep:UnnecessaryParentheses:OFF', // noisy
- '-Xep:UnnecessaryStringBuilder:WARN',
- // '-Xep:UnnecessaryTestMethodPrefix:OFF', // stylistic
- // '-Xep:UnqualifiedYield:OFF', // javac takes care
- '-Xep:UnrecognisedJavadocTag:WARN',
- // '-Xep:UnsafeFinalization:OFF', // we don't use finalizers, deprecated for removal, fails build
- '-Xep:UnsafeReflectiveConstructionCast:WARN',
- // '-Xep:UnsynchronizedOverridesSynchronized:OFF', // TODO: there are problems
- // '-Xep:UnusedLabel:OFF', // TODO: there are problems
- // '-Xep:UnusedMethod:OFF', // TODO: there are problems
- '-Xep:UnusedNestedClass:WARN',
- // '-Xep:UnusedTypeParameter:OFF', // TODO: there are problems
- // '-Xep:UnusedVariable:OFF', // noisy, can use ECJ
- // '-Xep:UseBinds:OFF', // we don't use this annotation
- // '-Xep:UseCorrectAssertInTests:OFF', // noisy
- '-Xep:VariableNameSameAsType:WARN',
- '-Xep:VoidUsed:WARN',
- // '-Xep:WaitNotInLoop:OFF', // TODO: there are problems
- // '-Xep:WakelockReleasedDangerously:OFF', // we don't use android
- // '-Xep:WithSignatureDiscouraged:OFF', // we aren't using this error-prone internal api
- ]
- }
- }
- }
-}
diff --git a/gradle/validation/forbidden-apis.gradle b/gradle/validation/forbidden-apis.gradle
deleted file mode 100644
index ebf5aff5d72..00000000000
--- a/gradle/validation/forbidden-apis.gradle
+++ /dev/null
@@ -1,183 +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 configures application of forbidden API rules
-// via https://github.com/policeman-tools/forbidden-apis
-
-def resources = scriptResources(buildscript)
-
-// Only apply forbidden-apis to java projects.
-allprojects { prj ->
- plugins.withId("java", {
- prj.apply plugin: 'de.thetaphi.forbiddenapis'
-
- // This helper method appends signature files based on a set of true
- // dependencies from a given configuration.
- def dynamicSignatures = { configuration, suffix ->
- def resolvedMods = configuration.resolvedConfiguration.resolvedArtifacts
- .collect { a -> a.moduleVersion.id }
- def deps = resolvedMods
- .collect { id -> [
- "${id.group}.${id.name}.all.txt",
- "${id.group}.${id.name}.${suffix}.txt",
- ]}
- .flatten()
- .sort()
-
- deps += ["defaults.all.txt", "defaults.${suffix}.txt"]
-
- deps.each { sig ->
- def signaturesFile = file("${resources}/${sig}")
- if (signaturesFile.exists()) {
- logger.info("Signature file applied: ${sig}")
- signaturesFiles += files(signaturesFile)
- } else {
- logger.debug("Signature file omitted (does not exist): ${sig}")
- }
- }
-
- // commons-io is special: forbiddenapis has a versioned bundledSignature.
- bundledSignatures += resolvedMods
- .findAll { id -> id.group == 'commons-io' && id.name == 'commons-io' }
- .collect { id -> "${id.name}-unsafe-${id.version}" as String }
- }
-
- // Configure defaults for sourceSets.main
- tasks.matching { it.name ==~ /forbiddenApisMain\d*/ }.configureEach {
- bundledSignatures += [
- 'jdk-unsafe',
- 'jdk-deprecated',
- 'jdk-non-portable',
- 'jdk-reflection',
- 'jdk-system-out',
- ]
-
- suppressAnnotations += [
- "**.SuppressForbidden"
- ]
-
- doFirst dynamicSignatures.curry(configurations.compileClasspath, "lucene")
- }
-
- // Configure defaults for the MR-JAR feature sourceSets by setting java version and ignore missing classes
- // TODO:
- // - Get hold of warning messages, see https://github.com/policeman-tools/forbidden-apis/issues/207
- tasks.matching { it.name ==~ /forbiddenApisMain\d+/ }.configureEach {
- failOnMissingClasses = false
- }
-
- // Configure defaults for sourceSets.test
- tasks.matching { it.name in ["forbiddenApisTest", "forbiddenApisTestFixtures"] }.configureEach {
- bundledSignatures += [
- 'jdk-unsafe',
- 'jdk-deprecated',
- 'jdk-non-portable',
- 'jdk-reflection',
- ]
-
- signaturesFiles = files(
- file("${resources}/defaults.tests.txt")
- )
-
- suppressAnnotations += [
- "**.SuppressForbidden"
- ]
-
- if (it.name == "forbiddenApisTestFixtures") {
- doFirst dynamicSignatures.curry(configurations.testFixturesCompileClasspath, "lucene")
- } else {
- doFirst dynamicSignatures.curry(configurations.testCompileClasspath, "lucene")
- }
- }
-
- // Configure defaults for sourceSets.tools (if present).
- tasks.matching { it.name == "forbiddenApisTools" }.configureEach {
- bundledSignatures += [
- 'jdk-unsafe',
- 'jdk-deprecated',
- 'jdk-non-portable',
- 'jdk-reflection',
- ]
-
- suppressAnnotations += [
- "**.SuppressForbidden"
- ]
-
- doFirst dynamicSignatures.curry(configurations.toolsCompileClasspath, "lucene")
-
- inputs.dir(file(resources))
- }
-
- // We rely on resolved configurations to compute the relevant set of rule
- // files for forbiddenApis. Since we don't want to resolve these configurations until
- // the task is executed, we can't really use them as task inputs properly. This is a
- // chicken-and-egg problem.
- //
- // This is the simplest workaround possible: just point at all the rule files and indicate
- // them as inputs. This way if a rule is modified, checks will be reapplied.
- tasks.matching { it.name.startsWith("forbiddenApis") }.configureEach { task ->
- task.inputs.dir(file(resources))
- }
-
- // Disable sysout signatures for these projects.
- if (prj.name in ["missing-doclet", "build-infra"]) {
- forbiddenApisMain.bundledSignatures -= [
- 'jdk-non-portable',
- 'jdk-system-out'
- ]
-
- forbiddenApisMain.exclude("**/Checksum*")
- forbiddenApisMain.suppressAnnotations += [
- "**.*SuppressForbidden"
- ]
- }
-
- if (prj.name in ["missing-doclet"] || prj.path in [
- ":lucene:demo",
- ":lucene:benchmark",
- ":lucene:test-framework"
- ]) {
- forbiddenApisMain.bundledSignatures -= [
- 'jdk-system-out'
- ]
- }
-
- // the test-framework module is special in that its main sources are exported for all tests.
- // include the test signature file (defaults.tests.txt) to the main sourceset.
- if (prj.path in [
- ":lucene:test-framework"
- ]) {
- forbiddenApisMain.signaturesFiles += files(
- file("${resources}/defaults.tests.txt")
- )
- }
-
- // apply logging patterns for all modules except Luke.
- if (prj.path !in [
- ":lucene:luke"
- ]) {
- forbiddenApisMain.signaturesFiles += files(
- file("${resources}/defaults.logging.txt")
- )
- }
-
- // disable forbidden apis for snowball code
- if (prj.path == ":lucene:analysis:common") {
- forbiddenApisMain.exclude("org/tartarus/**")
- }
- })
-}
diff --git a/gradle/validation/git-status.gradle b/gradle/validation/git-status.gradle
deleted file mode 100644
index fa976589836..00000000000
--- a/gradle/validation/git-status.gradle
+++ /dev/null
@@ -1,106 +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 verifies local git repository's status.
-
-import org.eclipse.jgit.api.*
-import org.eclipse.jgit.storage.file.FileRepositoryBuilder
-import org.eclipse.jgit.errors.*
-
-import java.nio.file.FileVisitResult
-import java.nio.file.Files
-import java.nio.file.SimpleFileVisitor
-import java.nio.file.Path
-import java.nio.file.attribute.BasicFileAttributes
-
-buildscript {
- repositories {
- mavenCentral()
- }
-
- dependencies {
- classpath deps.jgit
- }
-}
-
-configure(rootProject) {
- task gitStatus() {
- doFirst {
- try {
- def repository = new FileRepositoryBuilder()
- .setWorkTree(rootProject.projectDir)
- .setMustExist(true)
- .build()
-
- def ref = repository.findRef("HEAD").getObjectId()
- project.ext.gitRev = ref.name()
- project.ext.gitRevShort = ref.abbreviate(8).name()
- project.ext.gitStatus = new Git(repository).status().call()
- } catch (RepositoryNotFoundException | NoWorkTreeException e) {
- project.ext.gitRev = "(not a git checkout)"
- project.ext.gitRevShort = "(not a git checkout)"
- project.ext.gitStatus = null
- } catch (NotSupportedException e) {
- throw new GradleException("jgit does not support git repository version at this location: ${dir}", e)
- }
- }
- }
-
- // Verify git working copy does not have any unstaged modified files.
- task checkWorkingCopyClean() {
- dependsOn gitStatus
- doFirst {
- def status = rootProject.ext.gitStatus
- if (status == null) {
- if (file("${rootProject.projectDir}/.git").exists()) {
- // Ignore git worktree branches until jgit supports them.
- logger.warn("WARNING: git worktrees are not supported by jgit (won't check dirty files): ${rootProject.projectDir}")
- } else {
- // Ignore the check. This isn't a git checkout.
- logger.warn("WARNING: Directory is not a valid git checkout (won't check dirty files): ${rootProject.projectDir}")
- }
- } else {
- def offenders = [
- // Exclude staged changes. These are fine in precommit.
- // "(added)": status.added,
- // "(changed)": status.changed,
- // "(removed)": status.removed,
- "(conflicting)": status.conflicting,
- "(missing)": status.missing,
- "(modified)": status.modified,
- "(untracked)": status.untracked
- ].collectMany { fileStatus, files ->
- files.collect {file -> " - ${file} ${fileStatus}" }
- }.sort()
-
- if (offenders) {
- def checkProp = "validation.git.failOnModified"
- def shouldFail = Boolean.valueOf(propertyOrDefault(checkProp, true))
- def message = "Working copy is not a clean git checkout" +
- (shouldFail ? " (skip with -P${checkProp}=false)" : "") +
- ", offending files:\n${offenders.join("\n")}"
-
- if (shouldFail) {
- throw new GradleException(message)
- } else {
- logger.lifecycle("NOTE: ${message}")
- }
- }
- }
- }
- }
-}
diff --git a/gradle/validation/owasp-dependency-check/exclusions.xml b/gradle/validation/owasp/exclusions.xml
similarity index 100%
rename from gradle/validation/owasp-dependency-check/exclusions.xml
rename to gradle/validation/owasp/exclusions.xml
diff --git a/gradle/validation/precommit.gradle b/gradle/validation/precommit.gradle
deleted file mode 100644
index 06d65bca8ca..00000000000
--- a/gradle/validation/precommit.gradle
+++ /dev/null
@@ -1,49 +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 top-level 'precommit' task.
-
-configure(rootProject) {
- task precommit() {
- group = 'Precommit'
- description = "All precommit checks"
-
- // Root-level validation tasks.
- dependsOn ":checkLocks"
- dependsOn ":checkWorkingCopyClean"
- }
-
- // Attach all these tasks from all projects that have them.
- // This uses lazy collections as they may not yet be defined.
- allprojects { prj ->
- precommit.dependsOn prj.tasks.matching { task ->
- return task.name.endsWith("ChecksumCheck") ||
- task.name in [
- "forbiddenApis",
- "licenses",
- "rat",
- "ecjLint",
- "validateSourcePatterns",
- "spotlessCheck"
- ]}
- }
-
- // Each validation task should be attached to check but make sure
- // precommit() as a whole is a dependency on rootProject.check
- check.dependsOn precommit
-}
-
diff --git a/gradle/validation/rat-sources.gradle b/gradle/validation/rat-sources.gradle
deleted file mode 100644
index 3c59b4d2fe8..00000000000
--- a/gradle/validation/rat-sources.gradle
+++ /dev/null
@@ -1,245 +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 groovy.xml.NamespaceBuilder
-
-// Configure rat dependencies for use in the custom task.
-
-// Configure the rat validation task and all scanned directories.
-allprojects {
- configurations {
- ratDeps
- }
-
- dependencies {
- ratDeps deps.rat
- }
-
- tasks.register("rat", RatTask).configure {
- group = 'Verification'
- description = 'Runs Apache Rat checks.'
-
- dependsOn configurations.ratDeps
-
- def defaultScanFileTree = project.fileTree(projectDir, {
- // Don't check under the project's build folder.
- exclude project.buildDir.name
-
- // Exclude any generated stuff.
- exclude "src/generated"
-
- // Don't check any of the subprojects - they have their own rat tasks.
- exclude subprojects.collect { it.projectDir.name }
-
- // At the module scope we only check selected file patterns as folks have various .gitignore-d resources
- // generated by IDEs, etc.
- include "**/*.gradle"
- include "**/*.xml"
- include "**/*.md"
- include "**/*.py"
- include "**/*.sh"
- include "**/*.bat"
-
- // Include selected patterns from any source folders. We could make this
- // relative to source sets but it seems to be of little value - all our source sets
- // live under 'src' anyway.
- include "src/**"
- exclude "src/**/*.png"
- exclude "src/**/*.txt"
- exclude "src/**/*.zip"
- exclude "src/**/*.properties"
- exclude "src/**/*.utf8"
-
- // Conditionally apply module-specific patterns. We do it here instead
- // of reconfiguring each project because the provider can be made lazy
- // and it's easier to manage this way.
- switch (project.path) {
- case ":":
- include "gradlew"
- include "gradlew.bat"
- exclude ".gradle"
- exclude ".idea"
- exclude ".muse"
- exclude ".git"
-
- // Exclude github stuff (templates, workflows).
- exclude ".github"
-
- // The root project also includes patterns for the include composite
- // projects. Include their sources in the scan.
- include "build-tools/build-infra/src/**"
- include "build-tools/missing-doclet/src/**"
-
- // do not let RAT attempt to scan a python venv, it gets lost and confused...
- exclude "dev-tools/aws-jmh/build/**"
- exclude "dev-tools/scripts/.venv/**"
- break
-
- case ":lucene:analysis:morfologik":
- exclude "src/**/*.info"
- exclude "src/**/*.input"
- break
-
- case ":lucene:analysis:opennlp":
- exclude "src/**/en-test-lemmas.dict"
- break
-
- case ":lucene:demo":
- exclude "src/**/knn-token-vectors"
- break
-
- case ":lucene:test-framework":
- exclude "src/**/europarl.lines.txt.seek"
- break
-
- case ":lucene:analysis:common":
- case ":lucene:analysis.tests":
- exclude "src/**/*.aff"
- exclude "src/**/*.dic"
- exclude "src/**/*.good"
- exclude "src/**/*.sug"
- exclude "src/**/*.wrong"
- exclude "src/**/charfilter/*.htm*"
- exclude "src/**/*LuceneResourcesWikiPage.html"
- exclude "src/**/*.rslp"
- break
-
- case ":lucene:benchmark":
- exclude "data/"
- break
- }
- })
- inputFileTrees.add(defaultScanFileTree)
- }
-}
-
-/**
- * An Apache RAT adapter that validates whether files contain acceptable licenses.
- */
-@CacheableTask
-class RatTask extends DefaultTask {
-
- @InputFiles
- @PathSensitive(PathSensitivity.RELATIVE)
- @IgnoreEmptyDirectories
- final ListProperty<ConfigurableFileTree> inputFileTrees = project.objects.listProperty(ConfigurableFileTree)
-
- @OutputFile
- final RegularFileProperty xmlReport = project.objects.fileProperty().convention(
- project.layout.buildDirectory.file("rat/rat-report.xml"))
-
- def generateReport(File reportFile) {
- // Set up ant rat task.
- def ratClasspath = project.configurations.ratDeps.asPath
- ant.setLifecycleLogLevel(AntBuilder.AntMessagePriority.ERROR)
- ant.taskdef(resource: 'org/apache/rat/anttasks/antlib.xml', classpath: ratClasspath)
-
- // Collect all output files for debugging.
- String inputFileList = inputFileTrees.get().collectMany { fileTree ->
- fileTree.asList()
- }.sort().join("\n")
- project.file(reportFile.path.replaceAll('.xml$', '-filelist.txt')).setText(inputFileList, "UTF-8")
-
- // Run rat via ant.
- ant.report(format: 'xml', reportFile: reportFile, addDefaultLicenseMatchers: true) {
- // Pass all gradle file trees to the ant task (Gradle's internal adapters are used).
- inputFileTrees.get().each { fileTree ->
- fileTree.addToAntBuilder(ant, 'resources', FileCollection.AntType.ResourceCollection)
- }
-
- // BSD 4-clause stuff (is disallowed below)
- substringMatcher(licenseFamilyCategory: "BSD4 ", licenseFamilyName: "Original BSD License (with advertising clause)") {
- pattern(substring: "All advertising materials")
- }
-
- // BSD-like stuff
- substringMatcher(licenseFamilyCategory: "BSD ", licenseFamilyName: "Modified BSD License") {
- // brics automaton
- pattern(substring: "Copyright (c) 2001-2009 Anders Moeller")
- // snowball
- pattern(substring: "Copyright (c) 2001, Dr Martin Porter")
- // UMASS kstem
- pattern(substring: "THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF MASSACHUSETTS AND OTHER CONTRIBUTORS")
- // Egothor
- pattern(substring: "Egothor Software License version 1.00")
- // JaSpell
- pattern(substring: "Copyright (c) 2005 Bruno Martins")
- // d3.js
- pattern(substring: "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS")
- // highlight.js
- pattern(substring: "THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS")
- }
-
- // MIT-like
- substringMatcher(licenseFamilyCategory: "MIT ", licenseFamilyName:"Modified BSD License") {
- // ICU license
- pattern(substring: "Permission is hereby granted, free of charge, to any person obtaining a copy")
- // ui-grid
- pattern(substring: " ; License: MIT")
- }
-
- // Apache
- substringMatcher(licenseFamilyCategory: "AL ", licenseFamilyName: "Apache") {
- pattern(substring: "Licensed to the Apache Software Foundation (ASF) under")
- // this is the old - school one under some files
- pattern(substring: 'Licensed under the Apache License, Version 2.0 (the "License")')
- }
-
- substringMatcher(licenseFamilyCategory: "GEN ", licenseFamilyName: "Generated") {
- // svg files generated by gnuplot
- pattern(substring: "Produced by GNUPLOT")
- // snowball stemmers generated by snowball compiler
- pattern(substring: "Generated by Snowball")
- // parsers generated by antlr
- pattern(substring: "ANTLR GENERATED CODE")
- }
-
- approvedLicense(familyName: "Apache")
- approvedLicense(familyName: "The MIT License")
- approvedLicense(familyName: "Modified BSD License")
- approvedLicense(familyName: "Generated")
- }
- }
-
- def printUnknownFiles(File reportFile) {
- def ratXml = new XmlParser().parse(reportFile)
- def errors = []
- ratXml.resource.each { resource ->
- if (resource.'license-approval'.@name[0] == "false") {
- errors << "Unknown license: ${resource.@name}"
- }
- }
- if (errors) {
- throw new GradleException("Found " + errors.size() + " file(s) with errors:\n" +
- errors.collect{ msg -> " - ${msg}" }.join("\n"))
- }
- }
-
- @TaskAction
- def execute() {
- def origEncoding = System.getProperty("file.encoding")
- try {
- File reportFile = xmlReport.get().asFile
- generateReport(reportFile)
- printUnknownFiles(reportFile)
- } finally {
- if (System.getProperty("file.encoding") != origEncoding) {
- throw new GradleException("Something is wrong: Apache RAT changed file.encoding to ${System.getProperty('file.encoding')}?")
- }
- }
- }
-}
diff --git a/gradle/validation/spotless.gradle b/gradle/validation/spotless.gradle
deleted file mode 100644
index a77829a7032..00000000000
--- a/gradle/validation/spotless.gradle
+++ /dev/null
@@ -1,118 +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-9564: This adds automatic (and enforced) code formatting using
- * spotless and Google Java Format.
- */
-
-// def resources = scriptResources(buildscript)
-
-configure(allprojects) { prj ->
- plugins.withType(JavaPlugin) {
- prj.apply plugin: 'com.diffplug.spotless'
-
- spotless {
- java {
- // TODO: Work out how to support multiple different header files (we have
- // classes in the codebase that have original headers). We currently use
- // Apache RAT to enforce headers so this is of lesser priority.
- //
- // licenseHeaderFile file("${resources}/asl-header.txt"), '^(\\s*package)'
-
- lineEndings 'UNIX'
- endWithNewline()
- googleJavaFormat(deps.versions.googleJavaFormat.get())
-
- // Apply to all Java sources
- target "src/**/*.java"
-
- // Exclude certain files (generated ones, mostly).
- switch (project.path) {
- case ":lucene:core":
- targetExclude "**/StandardTokenizerImpl.java"
- break
-
- case ":lucene:analysis:common":
- targetExclude "**/HTMLStripCharFilter.java",
- "**/UAX29URLEmailTokenizerImpl.java"
- break
-
- case ":lucene:test-framework":
- targetExclude "**/EmojiTokenizationTestUnicode_11_0.java",
- "**/WordBreakTestUnicode_9_0_0.java"
- break
-
- case ":lucene:expressions":
- break
-
- case ":lucene:queryparser":
- targetExclude "**/classic/ParseException.java",
- "**/classic/QueryParser.java",
- "**/classic/QueryParserConstants.java",
- "**/classic/QueryParserTokenManager.java",
- "**/classic/Token.java",
- "**/classic/TokenMgrError.java",
- "**/standard/parser/ParseException.java",
- "**/standard/parser/StandardSyntaxParser.java",
- "**/standard/parser/StandardSyntaxParserConstants.java",
- "**/standard/parser/StandardSyntaxParserTokenManager.java",
- "**/standard/parser/Token.java",
- "**/standard/parser/TokenMgrError.java",
- "**/surround/parser/ParseException.java",
- "**/surround/parser/QueryParser.java",
- "**/surround/parser/QueryParserConstants.java",
- "**/surround/parser/QueryParserTokenManager.java",
- "**/surround/parser/Token.java",
- "**/surround/parser/TokenMgrError.java"
- break
- }
- }
- }
-
- // Workaround for an odd problem in spotless where it fails because
- // of a missing folder.
- spotlessJava {
- doFirst {
- project.mkdir("${buildDir}/spotless/spotlessJava")
- }
- }
-
- // Schedule the core formatting task to run after Java compilation (GH-12012)
- spotlessJava {
- mustRunAfter tasks.withType(JavaCompile)
- }
- }
-
- // Emit a custom message about how to fix formatting errors.
- tasks.matching { task -> task.name == "spotlessJavaCheck" }.configureEach {
- it.runToFixMessage.set("\nIMPORTANT: run the top-level './gradlew tidy' to format code automatically (see help/formatting.txt for more info).")
- }
-
- // Hook up spotless to tidy and check tasks.
- tasks.matching { it.name == "tidy" }.configureEach { v ->
- v.dependsOn tasks.matching { it.name == "spotlessApply" }
- }
-
- tasks.matching { it.name == "check" }.configureEach { v ->
- v.dependsOn tasks.matching { it.name == "spotlessCheck" }
- }
-
- tasks.matching { task -> task.name in ["spotlessApply", "spotlessCheck"] }.configureEach { v ->
- v.dependsOn ":checkJdkInternalsExportedToGradle"
- }
-}
diff --git a/gradlew b/gradlew
index b891547318a..890b0b17de4 100755
--- a/gradlew
+++ b/gradlew
@@ -205,9 +205,6 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
-# Prevent jgit from forking/searching git.exe
-export GIT_CONFIG_NOSYSTEM=1
-
# LUCENE-9471: workaround for gradle leaving junk temp. files behind.
GRADLE_TEMPDIR="$APP_HOME/.gradle/tmp"
mkdir -p "$GRADLE_TEMPDIR"
diff --git a/gradlew.bat b/gradlew.bat
index 803ed5ffb2b..3f2e1ab3549 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -107,9 +107,6 @@ IF NOT EXIST "%APP_HOME%\gradle.properties" (
endlocal
)
-@rem Prevent jgit from forking/searching git.exe
-SET GIT_CONFIG_NOSYSTEM=1
-
@rem END OF LUCENE CUSTOMIZATION
@rem Execute Gradle
diff --git a/help/localSettings.txt b/help/localSettings.txt
index 64c90c54eb6..c8a33f965c6 100644
--- a/help/localSettings.txt
+++ b/help/localSettings.txt
@@ -1,8 +1,39 @@
-Local developer settings
-========================
+Local gradle settings
+=====================
The first invocation of any task in Lucene's gradle build will generate
and save a project-local 'gradle.properties' file from a template,
-with some default settings which you can modify.
+with some default gradle JVM settings, which you can modify to your needs.
See your 'gradle.properties' file for more details of those settings.
+
+
+Build options
+=============
+
+There are also various options that the Lucene build uses, which can affect
+how tests are run or enable additional features (for example enable code
+coverage or profiling).
+
+To see the current values of all these options, run:
+
+./gradlew buildOptions
+
+this prints all build options for each module. You can also scope
+this task to just one module, for example:
+
+./gradlew -p lucene/core buildOptions
+
+The output of this task shows all options, their current values
+and their current value's "source". All build option values can be
+overridden by, in order of priority:
+
+ * cli parameters to gradlew (system properties): -DoptionKey=value
+ * cli parameters to gradlew (gradle properties): -PoptionKey=value
+ * env variables: optionKey=value ./gradlew ...
+ * property file (local for you, non-versioned!): build-options.local.properties
+ * property file (versioned): build-options.properties
+
+If you'd like to tweak some of the build options permanently, use the
+build-options.local.properties file. For temporary overrides, use
+cli parameters (preferably gradle parameters -Pxyz=value).
diff --git a/help/publishing.txt b/help/publishing.txt
index 0b237b039e3..f4ac0bdab1a 100644
--- a/help/publishing.txt
+++ b/help/publishing.txt
@@ -70,14 +70,14 @@ of secure passing of private key information and passwords.
Artifact signing using an external GPG with GPG Agent
-----------------------------------------------------
-You can use an external GPG command to deal with signing artifacts, with out needing to give gradle your passphrase,
-by adding a "-PuseGpg" option, but this changes the properties you must specify:
+You can use an external GPG command to deal with signing artifacts, without needing to give gradle your passphrase,
+by adding a "-PuseGpg=true" option, but this changes the properties you must specify:
For gpg2:
-gradlew [tasks] -Psign -PuseGpg -Psigning.gnupg.keyName=...
+gradlew [tasks] -Psign -PuseGpg=true -Psigning.gnupg.keyName=...
For gpg:
-gradlew [tasks] -Psign -PuseGpg -Psigning.gnupg.keyName=... -Psigning.gnupg.useLegacyGpg=true
+gradlew [tasks] -Psign -PuseGpg=true -Psigning.gnupg.keyName=... -Psigning.gnupg.useLegacyGpg=true
The keyName is the last 8 digits of your key (gpg -k will print your keys).
@@ -93,13 +93,13 @@ If in doubt, consult gradle's signing plugin documentation:
https://docs.gradle.org/current/userguide/signing_plugin.html#sec:using_gpg_agent
"signing.gnupg.passphrase" is not recommended because there is no advantage to using an external GPG process if you use it.
-If you are comfortable giving gradle your passphrase, then there is no reason to use an external GPG process via '-PuseGpg'.
-Just use the "signing.*" options described previuosly to let gradle deal with your key directly.
+If you are comfortable giving gradle your passphrase, then there is no reason to use an external GPG process via '-PuseGpg=true'.
+Just use the "signing.*" options described previously to let gradle deal with your key directly.
Because of how Gradle's signing plugin invokes GPG, using an external GPG process *only* works if your GPG configuration uses a
GPG agent (required by gpg2) and if the "pinentry" for your GPG agent does not require access to the tty to prompt you for a password.
-If you the following command fails with your GPG configuration, you can not use an external GPG process with gradle:
+If the following command fails with your GPG configuration, you can not use an external GPG process with gradle:
echo foo | gpg --batch --no-tty --armor --detach-sign --use-agent --local-user YOUR_KEY_NAME
diff --git a/help/tests.txt b/help/tests.txt
index d683395617b..7e12b6c5585 100644
--- a/help/tests.txt
+++ b/help/tests.txt
@@ -97,9 +97,9 @@ gradlew -p lucene/core test --tests TestDemo -Ptests.iters=5
Tests tasks will be (by default) re-executed on each invocation because
we pick a random global tests.seed and because we want them to (force
the test task to run). If you want to make the 'tests' task obey up-to-date
-gradle rules, fix the seed and turn off up to date trigger:
+gradle rules, fix the seed and force rerunning:
-gradlew -p lucene/core test -Ptests.seed=deadbeef -Ptests.neverUpToDate=false
+gradlew -p lucene/core test -Ptests.seed=deadbeef -Ptests.rerun=true
These properties can be set in your local gradle.properties. To force re-execution
of tests, even for the same master seed, apply cleanTest task:
@@ -137,9 +137,9 @@ Larger heap size
--------------------------
By default tests run with a 512 MB max heap. But some tests (monster/nightly)
-need more heap. Use "-Dtests.heapsize" for this:
+need more heap. Use "-Ptests.heapsize" for this:
- gradlew -p lucene/core test --tests "Test2BFST" -Dtests.heapsize=32g
+ gradlew -p lucene/core test --tests "Test2BFST" -Ptests.heapsize=32g
Run GUI tests headlessly with Xvfb (Linux only)
diff --git a/lucene/analysis.tests/build.gradle b/lucene/analysis.tests/build.gradle
index be1c51fecac..67efce2b9b9 100644
--- a/lucene/analysis.tests/build.gradle
+++ b/lucene/analysis.tests/build.gradle
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
-
description = 'Module integration tests for all :lucene:analysis modules'
dependencies {
diff --git a/lucene/analysis/common/build.gradle b/lucene/analysis/common/build.gradle
index 98925b8a2d2..0cb5524881c 100644
--- a/lucene/analysis/common/build.gradle
+++ b/lucene/analysis/common/build.gradle
@@ -15,9 +15,12 @@
* limitations under the License.
*/
+
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOption
+
import java.nio.file.Files;
-apply plugin: 'java-library'
+
description = 'Analyzers for indexing content in different languages and domains'
@@ -40,16 +43,16 @@ def cloneDirProperty = project.layout.buildDirectory.dir("hunspell-regressions")
// a full commit reference for each project. These should be updated
// from time to time based on what's available at the head reference.
def dictionaryProjects = [
- [
- "name": "libreoffice",
- "url": "https://github.com/LibreOffice/dictionaries",
- "ref": "762abe74008b94b2ff06db6f4024b59a8254c467" // head: master
- ],
- [
- "name": "woorm",
- "url": "https://github.com/wooorm/dictionaries",
- "ref": "8cfea406b505e4d7df52d5a19bce525df98c54ab" // head: main
- ]
+ [
+ "name": "libreoffice",
+ "url": "https://github.com/LibreOffice/dictionaries",
+ "ref": "762abe74008b94b2ff06db6f4024b59a8254c467" // head: master
+ ],
+ [
+ "name": "woorm",
+ "url": "https://github.com/wooorm/dictionaries",
+ "ref": "8cfea406b505e4d7df52d5a19bce525df98c54ab" // head: main
+ ]
]
// We need this for the new gradle configuration cache. I personally think it's
@@ -81,10 +84,10 @@ def cloningTasks = dictionaryProjects.collect { repoSpec ->
def logger = task.logger
def dotGitPath = targetDir.get().asFile.toPath().toAbsolutePath().resolve(".git")
- def gitExec = (List<String> cmdArgs) -> {
+ def gitExec = { List<String> cmdArgs ->
logger.lifecycle("Executing git " + cmdArgs.join(" "))
execOps.exec {
- executable "git"
+ executable project.externalTool("git")
ignoreExitValue false
workingDir dotGitPath.getParent().toString()
args = cmdArgs
@@ -98,14 +101,33 @@ def cloningTasks = dictionaryProjects.collect { repoSpec ->
// the remote url (origin) but don't fetch anything.
if (!Files.exists(dotGitPath)) {
Files.createDirectories(dotGitPath.getParent())
- gitExec(["init", "--initial-branch", "irrelevant"])
- gitExec(["config", "advice.detachedHead", "false"])
- gitExec(["remote", "add", "origin", repoSpec.url])
+ gitExec([
+ "init",
+ "--initial-branch",
+ "irrelevant"
+ ])
+ gitExec([
+ "config",
+ "advice.detachedHead",
+ "false"
+ ])
+ gitExec([
+ "remote",
+ "add",
+ "origin",
+ repoSpec.url
+ ])
}
// Fetch just the revision we're interested in.
// This avoids downloading the entire repo.
- gitExec(["fetch", "--depth", "1", "origin", ref.get()])
+ gitExec([
+ "fetch",
+ "--depth",
+ "1",
+ "origin",
+ ref.get()
+ ])
gitExec(["checkout", "FETCH_HEAD"])
}
})
@@ -113,8 +135,10 @@ def cloningTasks = dictionaryProjects.collect { repoSpec ->
}
// check if we should run tests with hunspell dictionaries.
-def withDictionaries = Boolean.parseBoolean(propertyOrDefault("tests.hunspell.regressions", "false"))
-if (withDictionaries) {
+Provider<Boolean> testRegressionsOption = buildOptions.addBooleanOption("tests.hunspell.regressions",
+ "Include testing for regressions against hunspell dictionaries", false)
+
+if (testRegressionsOption.get()) {
tasks.withType(Test).configureEach {
dependsOn cloningTasks
inputs.dir cloneDirProperty
@@ -123,16 +147,21 @@ if (withDictionaries) {
}
// Pass all hunspell-tests-specific project properties to tests as system properties, if they're specified.
+buildOptions.addOption("hunspell.dictionaries", "Path to hunspell dictionaries for TestAllDictionaries.")
+buildOptions.addOption("hunspell.corpora", "Path to hunspell test work corpora for TestPerformance.")
+buildOptions.addOption("hunspell.repo.path", "Path to hunspell repo path for TestHunspellRepositoryTestCases")
+
tasks.withType(Test).configureEach {
[
- "hunspell.dictionaries",
- "hunspell.corpora",
- "hunspell.repo.path"
- ].each {
- def val = propertyOrDefault(it, null)
- if (val != null) {
- logger.lifecycle("Passing property: ${it}=${val}")
- systemProperty it, val
+ "hunspell.dictionaries",
+ "hunspell.corpora",
+ "hunspell.repo.path"
+ ].each {optionName ->
+ BuildOption option = buildOptions.getOption(optionName)
+ if (option.isPresent()) {
+ def val = option.asStringProvider().get()
+ logger.lifecycle("Passing property: ${optionName}=${val}")
+ systemProperty(optionName, val)
}
}
}
diff --git a/lucene/analysis/common/src/generated/checksums/generateClassicTokenizer.json b/lucene/analysis/common/src/generated/checksums/generateClassicTokenizer.json
index 93a7ae1b06a..e1aef642d78 100644
--- a/lucene/analysis/common/src/generated/checksums/generateClassicTokenizer.json
+++ b/lucene/analysis/common/src/generated/checksums/generateClassicTokenizer.json
@@ -1,5 +1,5 @@
{
- "gradle/generation/jflex/skeleton.default.txt": "58944f66c9113a940dfaf6a17210ec8219024390",
+ "gradle/regenerate/jflex/skeleton.default.txt": "58944f66c9113a940dfaf6a17210ec8219024390",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/classic/ClassicTokenizerImpl.java": "db0247e6c18327d1e21eb8f37495d81488655ff6",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/classic/ClassicTokenizerImpl.jflex": "f52109bb7d5701979fde90aeeeda726246a8d5fd"
}
\ No newline at end of file
diff --git a/lucene/analysis/common/src/generated/checksums/generateHTMLCharacterEntities.json b/lucene/analysis/common/src/generated/checksums/generateHTMLCharacterEntities.json
index 049b9b01d97..3fec92df9c2 100644
--- a/lucene/analysis/common/src/generated/checksums/generateHTMLCharacterEntities.json
+++ b/lucene/analysis/common/src/generated/checksums/generateHTMLCharacterEntities.json
@@ -1,4 +1,4 @@
{
- "gradle/generation/jflex/htmlentity.py": "66e0238fed4e069addbbdb93179b1457fc3a5203",
+ "gradle/regenerate/jflex/htmlentity.py": "66e0238fed4e069addbbdb93179b1457fc3a5203",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/HTMLCharacterEntities.jflex": "d1aa75b9b37646efe31731394f84a063eb7eed9d"
}
\ No newline at end of file
diff --git a/lucene/analysis/common/src/generated/checksums/generateHTMLStripCharFilter.json b/lucene/analysis/common/src/generated/checksums/generateHTMLStripCharFilter.json
index 3cac9a2f07a..e202ce03854 100644
--- a/lucene/analysis/common/src/generated/checksums/generateHTMLStripCharFilter.json
+++ b/lucene/analysis/common/src/generated/checksums/generateHTMLStripCharFilter.json
@@ -1,5 +1,5 @@
{
- "gradle/generation/jflex/skeleton.default.txt": "58944f66c9113a940dfaf6a17210ec8219024390",
+ "gradle/regenerate/jflex/skeleton.default.txt": "58944f66c9113a940dfaf6a17210ec8219024390",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/HTMLCharacterEntities.jflex": "d1aa75b9b37646efe31731394f84a063eb7eed9d",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.java": "a885fde83409dcc72881af98efe583c4bfac6540",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.jflex": "5320cb952146a3f9da93b98067a6ffbbb284dc0f"
diff --git a/lucene/analysis/common/src/generated/checksums/generateTlds.json b/lucene/analysis/common/src/generated/checksums/generateTlds.json
index 511524961b4..5a127950e8c 100644
--- a/lucene/analysis/common/src/generated/checksums/generateTlds.json
+++ b/lucene/analysis/common/src/generated/checksums/generateTlds.json
@@ -1,5 +1,5 @@
{
- "lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex": "94379f4c5f092067a657bdb960fb757f749900e3",
- "lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TLDs.txt": "f5d3f68534d0fbbc2ed4d4ce5773e7b5f1f9215f",
+ "lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex": "b7926d1e070e1fce661f5a4426cc9d0ef0a342b9",
+ "lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TLDs.txt": "327095c4470af74b8639b7d8b5b33bc4ef15df8c",
"property:tldZones": "https://data.iana.org/TLD/tlds-alpha-by-domain.txt"
}
\ No newline at end of file
diff --git a/lucene/analysis/common/src/generated/checksums/generateUAX29URLEmailTokenizer.json b/lucene/analysis/common/src/generated/checksums/generateUAX29URLEmailTokenizer.json
index c6116627880..1d3bccf9145 100644
--- a/lucene/analysis/common/src/generated/checksums/generateUAX29URLEmailTokenizer.json
+++ b/lucene/analysis/common/src/generated/checksums/generateUAX29URLEmailTokenizer.json
@@ -1,6 +1,6 @@
{
- "gradle/generation/jflex/skeleton.disable.buffer.expansion.txt": "6e43a3a64a9b5eb82ec5b4bc21f95aff5a2a061e",
- "lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex": "94379f4c5f092067a657bdb960fb757f749900e3",
+ "gradle/regenerate/jflex/skeleton.disable.buffer.expansion.txt": "6e43a3a64a9b5eb82ec5b4bc21f95aff5a2a061e",
+ "lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex": "b7926d1e070e1fce661f5a4426cc9d0ef0a342b9",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/email/UAX29URLEmailTokenizerImpl.java": "4b0c19f0addd45ed20a78ad865a6418191e0342c",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/email/UAX29URLEmailTokenizerImpl.jflex": "8d7cd1a935443deda6cad73b91f1a45c1c714535"
}
\ No newline at end of file
diff --git a/lucene/analysis/common/src/generated/checksums/generateWikipediaTokenizer.json b/lucene/analysis/common/src/generated/checksums/generateWikipediaTokenizer.json
index 72045518e8d..2f41cb11554 100644
--- a/lucene/analysis/common/src/generated/checksums/generateWikipediaTokenizer.json
+++ b/lucene/analysis/common/src/generated/checksums/generateWikipediaTokenizer.json
@@ -1,5 +1,5 @@
{
- "gradle/generation/jflex/skeleton.default.txt": "58944f66c9113a940dfaf6a17210ec8219024390",
+ "gradle/regenerate/jflex/skeleton.default.txt": "58944f66c9113a940dfaf6a17210ec8219024390",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/wikipedia/WikipediaTokenizerImpl.java": "288850d5a05c0428e7bd3aaf8d1204fdd5043746",
"lucene/analysis/common/src/java/org/apache/lucene/analysis/wikipedia/WikipediaTokenizerImpl.jflex": "0b8c7774b98e8237702013e82c352d4711509bd0"
}
\ No newline at end of file
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex b/lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex
index 2246f6b28bc..0c41e2272f6 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/email/ASCIITLD.jflex
@@ -15,7 +15,7 @@
* limitations under the License.
*/
// Generated from IANA TLD Database <https://data.iana.org/TLD/tlds-alpha-by-domain.txt>
-// file version from 2025 May 11, Sun 07:07:01 GMT
+// file version from 2025 Jun 6, Fri 07:07:01 GMT
// generated by org.apache.lucene.analysis.standard.GenerateJflexTLDMacros
// LUCENE-8278: None of the TLDs in {ASCIITLD} is a 1-character-shorter prefix of another TLD
@@ -844,7 +844,6 @@ ASCIITLD = "." (
| [pP][oO][lL][iI][tT][iI][eE]
| [pP][oO][rR][nN]
| [pP][oO][sS][tT]
- | [pP][rR][aA][mM][eE][rR][iI][cC][aA]
| [pP][rR][aA][xX][iI]
| [pP][rR][eE][sS][sS]
| [pP][rR][iI][mM][eE]
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TLDs.txt b/lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TLDs.txt
index fe8323324c8..b623151e642 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TLDs.txt
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TLDs.txt
@@ -911,7 +911,6 @@ politie
porn
post
pr
-pramerica
praxi
press
prime
diff --git a/lucene/analysis/icu/build.gradle b/lucene/analysis/icu/build.gradle
index 5550143224a..3bcde2832f4 100644
--- a/lucene/analysis/icu/build.gradle
+++ b/lucene/analysis/icu/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Analysis integration with ICU (International Components for Unicode)'
diff --git a/lucene/analysis/kuromoji/build.gradle b/lucene/analysis/kuromoji/build.gradle
index fd8aedbbc1e..9119a5c50fa 100644
--- a/lucene/analysis/kuromoji/build.gradle
+++ b/lucene/analysis/kuromoji/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Japanese Morphological Analyzer'
diff --git a/lucene/analysis/morfologik.tests/build.gradle b/lucene/analysis/morfologik.tests/build.gradle
index d2f94ddc33f..9d6842536f4 100644
--- a/lucene/analysis/morfologik.tests/build.gradle
+++ b/lucene/analysis/morfologik.tests/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Module tests for :lucene:analysis:morfologik'
diff --git a/lucene/analysis/morfologik/build.gradle b/lucene/analysis/morfologik/build.gradle
index 7c8b5910395..52c48e24284 100644
--- a/lucene/analysis/morfologik/build.gradle
+++ b/lucene/analysis/morfologik/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Analyzer for dictionary stemming, built-in Polish dictionary'
diff --git a/lucene/analysis/nori/build.gradle b/lucene/analysis/nori/build.gradle
index c84ade814f9..b9e82d0c90a 100644
--- a/lucene/analysis/nori/build.gradle
+++ b/lucene/analysis/nori/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Korean Morphological Analyzer'
@@ -25,4 +25,3 @@ dependencies {
moduleTestImplementation project(':lucene:test-framework')
}
-
diff --git a/lucene/analysis/opennlp/build.gradle b/lucene/analysis/opennlp/build.gradle
index da3a960ab08..ef056b664bb 100644
--- a/lucene/analysis/opennlp/build.gradle
+++ b/lucene/analysis/opennlp/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'OpenNLP Library Integration'
@@ -33,6 +33,7 @@ ext {
testModelDir = file("${testsUserDir}/org/apache/lucene/analysis/opennlp")
}
+// this should be hooked to regenerate?
tasks.register('trainTestModels') {
description = 'Train all small test models for unit tests'
doLast {
@@ -41,7 +42,10 @@ tasks.register('trainTestModels') {
trainModel('TokenizerTrainer', 'en', 'tokenizer.txt', 'en-test-tokenizer.bin')
trainModel('POSTaggerTrainer', 'en', 'pos.txt', 'en-test-pos-maxent.bin')
trainModel('ChunkerTrainerME', 'en', 'chunks.txt', 'en-test-chunker.bin')
- trainModel('TokenNameFinderTrainer', 'en', 'ner.txt', 'en-test-ner.bin', ['-params', 'ner_TrainerParams.txt'])
+ trainModel('TokenNameFinderTrainer', 'en', 'ner.txt', 'en-test-ner.bin', [
+ '-params',
+ 'ner_TrainerParams.txt'
+ ])
trainModel('LemmatizerTrainerME', 'en', 'lemmas.txt', 'en-test-lemmatizer.bin')
}
}
@@ -51,7 +55,14 @@ def trainModel(String command, String lang, String data, String model, List extr
classpath = sourceSets.main.compileClasspath
mainClass = 'opennlp.tools.cmdline.CLI'
workingDir = testModelDataDir
- args = [command, '-lang', lang, '-data', data, '-model', "${testModelDir}/${model}"] + extraArgs
+ args = [
+ command,
+ '-lang',
+ lang,
+ '-data',
+ data,
+ '-model',
+ "${testModelDir}/${model}"
+ ] + extraArgs
}
}
-
diff --git a/lucene/analysis/phonetic/build.gradle b/lucene/analysis/phonetic/build.gradle
index 81841ccfc3e..c504cb29898 100644
--- a/lucene/analysis/phonetic/build.gradle
+++ b/lucene/analysis/phonetic/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Analyzer for indexing phonetic signatures (for sounds-alike search)'
@@ -26,5 +26,4 @@ dependencies {
moduleApi deps.commons.codec
moduleTestImplementation project(':lucene:test-framework')
-}
-
+}
diff --git a/lucene/analysis/smartcn/build.gradle b/lucene/analysis/smartcn/build.gradle
index 87aafc971d6..872b7537c0e 100644
--- a/lucene/analysis/smartcn/build.gradle
+++ b/lucene/analysis/smartcn/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Analyzer for indexing Chinese'
@@ -24,4 +24,4 @@ dependencies {
moduleApi project(':lucene:analysis:common')
moduleTestImplementation project(':lucene:test-framework')
-}
+}
diff --git a/lucene/analysis/stempel/build.gradle b/lucene/analysis/stempel/build.gradle
index 52d1b816c5e..bf8ac1879e3 100644
--- a/lucene/analysis/stempel/build.gradle
+++ b/lucene/analysis/stempel/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Analyzer for indexing Polish'
diff --git a/lucene/backward-codecs/build.gradle b/lucene/backward-codecs/build.gradle
index 528c1a5aca5..7bc66783056 100644
--- a/lucene/backward-codecs/build.gradle
+++ b/lucene/backward-codecs/build.gradle
@@ -16,7 +16,7 @@
*/
-apply plugin: 'java-library'
+
description = 'Codecs for older versions of Lucene'
diff --git a/lucene/benchmark-jmh/build.gradle b/lucene/benchmark-jmh/build.gradle
index c94bc69cc52..d1ce843f470 100644
--- a/lucene/benchmark-jmh/build.gradle
+++ b/lucene/benchmark-jmh/build.gradle
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-plugins {
- id "java-library"
-}
-
description = 'Lucene JMH micro-benchmarking module'
dependencies {
@@ -34,21 +30,23 @@ dependencies {
// Exclude JMH-generated files and certain classes that require incubating classes
// from forbiddenapis validation.
tasks.matching { it.name == "forbiddenApisMain" }.configureEach {
- patternSet.exclude([
- "**/jmh_generated/**"
- ])
+ patternSet.exclude(["**/jmh_generated/**"])
}
// Skip certain infrastructure tasks that we can't use or don't care about.
-tasks.matching { it.name in [
+tasks.matching {
+ it.name in [
// Turn off JMH dependency checksums and licensing (it's GPL w/ classpath exception
// but this seems fine for test/build only tools).
- "validateJarChecksums", "validateJarLicenses", "collectJarInfos",
+ "validateJarChecksums",
+ "validateJarLicenses",
+ "collectJarInfos",
// No special javadocs for JMH benchmarks.
"renderSiteJavadoc",
"renderJavadoc",
-]}.configureEach {
+ ]
+}.configureEach {
it.enabled = false
}
@@ -73,13 +71,13 @@ jar.configure { Jar jarTask ->
manifest {
attributes([
- "Main-Class": "org.apache.lucene.benchmark.jmh.Main",
- "Class-Path": new Object () {
- @Override
- String toString() {
- return configurations.runtimeClasspath.collect { f -> f.name }.join(" ")
- }
+ "Main-Class": "org.apache.lucene.benchmark.jmh.Main",
+ "Class-Path": new Object () {
+ @Override
+ String toString() {
+ return configurations.runtimeClasspath.collect { f -> f.name }.join(" ")
}
+ }
])
}
}
@@ -99,7 +97,7 @@ java --module-path ${rootDir.toPath().relativize(dependenciesDir.toPath())} --mo
JMH options you can use with the above:
- -h displays verbose help for all options
+ -h displays verbose help for all options
-l list available benchmarks
-lp list benchmarks that pass the filter and their parameters
regexp execute all benchmark containing regexp
diff --git a/lucene/benchmark/build.gradle b/lucene/benchmark/build.gradle
index 70a1b31a6c1..4e98fc344d8 100644
--- a/lucene/benchmark/build.gradle
+++ b/lucene/benchmark/build.gradle
@@ -21,7 +21,7 @@ plugins {
description = 'Lucene benchmarking module'
-dependencies {
+dependencies {
moduleImplementation project(':lucene:core')
moduleImplementation project(':lucene:analysis:common')
@@ -56,20 +56,32 @@ sourceSets {
test.resources.srcDirs += ['conf']
}
-task run(type: JavaExec) {
- description "Run a perf test (optional: -PtaskAlg=conf/your-algorithm-file -PmaxHeapSize=1G). Before running this, you need to download the dataset the benchmark run against (e.g., by getReuters task). See dataset download tasks for more details."
- group "Utility launchers"
+def taskAlgOption = buildOptions.addFileOption("taskAlg", "Path to the task file for the 'run' task.",
+ layout.projectDirectory.file("conf/micro-standard.alg"))
+
+def heapSizeOption = buildOptions.addOption("maxHeapSize", "Heap size for the 'run' task.", "1G")
+
+def outputFileOption = buildOptions.addFileOption("standardOutput", "Path to the output file for the 'run' task.")
+
+tasks.register("run", JavaExec, {
+ description = "Run a perf test (optional: -PtaskAlg=conf/your-algorithm-file -PmaxHeapSize=1G). Before" +
+ " running this, you need to download the dataset the benchmark runs against (e.g., by getReuters" +
+ " task). See dataset download tasks for more details."
+ group = "Utility launchers"
+
mainClass = 'org.apache.lucene.benchmark.byTask.Benchmark'
classpath sourceSets.main.runtimeClasspath
+
// allow these to be specified on the CLI via -PtaskAlg= for example
- args = [propertyOrDefault('taskAlg', 'conf/micro-standard.alg')]
+ args = [
+ taskAlgOption.get().asFile.absolutePath
+ ]
- maxHeapSize = propertyOrDefault('maxHeapSize', '1G')
+ maxHeapSize = heapSizeOption.get()
- String stdOutStr = propertyOrDefault('standardOutput', null)
- if (stdOutStr != null) {
- standardOutput = new File(stdOutStr).newOutputStream()
+ if (outputFileOption.isPresent()) {
+ standardOutput = outputFileOption.get().asFile.newOutputStream()
}
debugOptions {
@@ -77,4 +89,4 @@ task run(type: JavaExec) {
port = 5005
suspend = true
}
-}
+})
diff --git a/lucene/build.gradle b/lucene/build.gradle
index 1d2d60830a1..0c1dd28a89e 100644
--- a/lucene/build.gradle
+++ b/lucene/build.gradle
@@ -16,7 +16,3 @@
*/
description = 'Parent project for Apache Lucene Core'
-
-subprojects {
- group "org.apache.lucene"
-}
diff --git a/lucene/classification/build.gradle b/lucene/classification/build.gradle
index 1b8a1bdb3fa..12d213afebb 100644
--- a/lucene/classification/build.gradle
+++ b/lucene/classification/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Classification module for Lucene'
diff --git a/lucene/codecs/build.gradle b/lucene/codecs/build.gradle
index 1de66fe9bbb..0492bdbf7ab 100644
--- a/lucene/codecs/build.gradle
+++ b/lucene/codecs/build.gradle
@@ -15,11 +15,11 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Lucene codecs and postings formats'
dependencies {
- moduleImplementation project(':lucene:core')
- moduleTestImplementation project(':lucene:test-framework')
+ moduleImplementation project(':lucene:core')
+ moduleTestImplementation project(':lucene:test-framework')
}
diff --git a/lucene/core.tests/build.gradle b/lucene/core.tests/build.gradle
index 4bc8bf5cef5..0343117789a 100644
--- a/lucene/core.tests/build.gradle
+++ b/lucene/core.tests/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Module tests for :lucene:core'
diff --git a/lucene/core/build.gradle b/lucene/core/build.gradle
index e55c0853f61..eddd4013560 100644
--- a/lucene/core/build.gradle
+++ b/lucene/core/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Lucene core library'
diff --git a/lucene/core/src/generated/checksums/generateStandardTokenizer.json b/lucene/core/src/generated/checksums/generateStandardTokenizer.json
index bcfbda06c20..77580f26f5f 100644
--- a/lucene/core/src/generated/checksums/generateStandardTokenizer.json
+++ b/lucene/core/src/generated/checksums/generateStandardTokenizer.json
@@ -1,5 +1,5 @@
{
- "gradle/generation/jflex/skeleton.disable.buffer.expansion.txt": "6e43a3a64a9b5eb82ec5b4bc21f95aff5a2a061e",
+ "gradle/regenerate/jflex/skeleton.disable.buffer.expansion.txt": "6e43a3a64a9b5eb82ec5b4bc21f95aff5a2a061e",
"lucene/core/src/java/org/apache/lucene/analysis/standard/StandardTokenizerImpl.java": "6b273988326aa6830905505506359a500083f608",
"lucene/core/src/java/org/apache/lucene/analysis/standard/StandardTokenizerImpl.jflex": "2db77654bcef8add1523d9e6260a3f72a3c58ed1"
}
\ No newline at end of file
diff --git a/lucene/core/src/generated/checksums/utilGenLev.json b/lucene/core/src/generated/checksums/utilGenLev.json
index 24dc1e85bce..8e4914c1a41 100644
--- a/lucene/core/src/generated/checksums/utilGenLev.json
+++ b/lucene/core/src/generated/checksums/utilGenLev.json
@@ -1,5 +1,5 @@
{
- "gradle/generation/moman/createLevAutomata.py": "d2ebb025aa51a3896f2f9435a756c7d733811b05",
+ "gradle/regenerate/moman/createLevAutomata.py": "d2ebb025aa51a3896f2f9435a756c7d733811b05",
"lucene/core/src/java/org/apache/lucene/util/automaton/Lev1ParametricDescription.java": "efa1e1aff2c75f32d5f6b35adb5cb346c50c9fe5",
"lucene/core/src/java/org/apache/lucene/util/automaton/Lev1TParametricDescription.java": "cda745cca726a46ec66b5a4ce1c983414d075f7d",
"lucene/core/src/java/org/apache/lucene/util/automaton/Lev2ParametricDescription.java": "6e0c90405874800d65e8344b4549cd749e009e90",
diff --git a/lucene/core/src/generated/checksums/utilGenPacked.json b/lucene/core/src/generated/checksums/utilGenPacked.json
index 10562224ed8..d911b2f9cc6 100644
--- a/lucene/core/src/generated/checksums/utilGenPacked.json
+++ b/lucene/core/src/generated/checksums/utilGenPacked.json
@@ -1,6 +1,6 @@
{
- "gradle/generation/moman/gen_BulkOperation.py": "d721930b5dae7f938b52a17700eb84b157930b2b",
- "gradle/generation/moman/gen_Packed64SingleBlock.py": "0fd2a498c3edbd195a68c2d1d686be0aed51a104",
+ "gradle/regenerate/moman/gen_BulkOperation.py": "d721930b5dae7f938b52a17700eb84b157930b2b",
+ "gradle/regenerate/moman/gen_Packed64SingleBlock.py": "0fd2a498c3edbd195a68c2d1d686be0aed51a104",
"lucene/core/src/java/org/apache/lucene/util/packed/BulkOperation.java": "c4e16930960a18e74802c56ee60f8e83bd8b6dd2",
"lucene/core/src/java/org/apache/lucene/util/packed/BulkOperationPacked.java": "2b0d9226bae8a07ce4970bcaa9d4d0cd4fe2c79a",
"lucene/core/src/java/org/apache/lucene/util/packed/BulkOperationPacked1.java": "c483aa35c275bacc1f3a010c5b879441be502108",
diff --git a/lucene/core/src/test/org/apache/lucene/index/Test2BPostingsBytes.java b/lucene/core/src/test/org/apache/lucene/index/Test2BPostingsBytes.java
index 8b90b1d610b..29abe55d780 100644
--- a/lucene/core/src/test/org/apache/lucene/index/Test2BPostingsBytes.java
+++ b/lucene/core/src/test/org/apache/lucene/index/Test2BPostingsBytes.java
@@ -63,7 +63,7 @@ public class Test2BPostingsBytes extends LuceneTestCase {
+ maxDocsPerChunk
+ ") * blockSize ("
+ blockSize
- + ") < 16 - this can trigger OOM with -Dtests.heapsize=30g",
+ + ") < 16 - this can trigger OOM with -Ptests.heapsize=30g",
product >= 16);
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/Test2BTerms.java b/lucene/core/src/test/org/apache/lucene/index/Test2BTerms.java
index de90a0ae1db..90ed7902aaf 100644
--- a/lucene/core/src/test/org/apache/lucene/index/Test2BTerms.java
+++ b/lucene/core/src/test/org/apache/lucene/index/Test2BTerms.java
@@ -51,7 +51,7 @@ import org.apache.lucene.util.BytesRef;
// disk (but, should run successfully). Best to run w/
// -Dtests.codec=<current codec>, and w/ plenty of RAM, eg:
//
-// ant test -Dtests.monster=true -Dtests.heapsize=8g -Dtests.codec=Lucene62 -Dtestcase=Test2BTerms
+// gradlew test -Ptests.monster=true -Ptests.heapsize=8g -Ptests.codec=Lucene62 --tests Test2BTerms
//
@SuppressCodecs({"SimpleText", "Direct"})
@Monster("very slow, use 5g minimum heap")
diff --git a/lucene/demo/build.gradle b/lucene/demo/build.gradle
index a5c9469c06e..854661370b1 100644
--- a/lucene/demo/build.gradle
+++ b/lucene/demo/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Simple example code for Apache Lucene'
diff --git a/lucene/distribution.tests/build.gradle b/lucene/distribution.tests/build.gradle
index 4513198c267..de4b2953361 100644
--- a/lucene/distribution.tests/build.gradle
+++ b/lucene/distribution.tests/build.gradle
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-plugins {
- id 'java-library'
-}
-
configurations {
// This is a configuration that references an 'folder-expanded' binary distribution
// tests will run against. The distribution is slightly trimmed (no docs, licenses)
@@ -48,16 +44,16 @@ test {
// https://github.com/gradle/gradle/issues/12247
// so we'll use a workaround and pass command-line arguments directly.
jvmArgumentProviders.add(new CommandLineArgumentProvider() {
- @Override
- Iterable<String> asArguments() {
- return [
- "-Dlucene.distribution.dir=${configurations.binaryDistribution.singleFile.absolutePath }",
- "-Dlucene.distribution.version=${project.version}"
- ]
- }
- })
+ @Override
+ Iterable<String> asArguments() {
+ return [
+ "-Dlucene.distribution.dir=${configurations.binaryDistribution.singleFile.absolutePath }",
+ "-Dlucene.distribution.version=${project.version}"
+ ]
+ }
+ })
doFirst {
logger.lifecycle("Testing binary distribution at: ${configurations.binaryDistribution.singleFile}")
}
-}
\ No newline at end of file
+}
diff --git a/lucene/distribution/build.gradle b/lucene/distribution/build.gradle
index d1f70a1abf9..80df4a6e778 100644
--- a/lucene/distribution/build.gradle
+++ b/lucene/distribution/build.gradle
@@ -25,17 +25,48 @@ plugins {
// This project puts together the Lucene "distribution", assembling bits and pieces
// from across the project structure into release artifacts.
+Provider<Boolean> signOption = buildOptions.addBooleanOption("sign", "Sign assembled distribution artifacts.", false)
+
ext {
releaseDir = file("${buildDir}/release")
- withSignedArtifacts = { ->
- def propValue = propertyOrDefault("sign", null)
- // Allow -Psign to work as a shorthand for -Psign=true
- return propValue != null && (propValue.isBlank() || Boolean.parseBoolean(propValue))
- }.call()
+ withSignedArtifacts = signOption.get()
}
-// Prepare the "source" distribution artifact.
-apply from: buildscript.sourceFile.toPath().resolveSibling("source-release.gradle")
+// Collect git revision.
+MapProperty<String, String> gitStatus = rootProject.extensions.getByName("gitinfo").getGitInfo()
+Provider<String> gitRev = gitStatus.getting("git.commit")
+
+// Prepare the "source" distribution artifact. We use raw git export, no additional complexity needed.
+Provider<RegularFile> sourceTgzFile = project.layout.buildDirectory.file("packages/lucene-${version}-src.tgz")
+tasks.register("assembleSourceTgz", {
+ description "Assemble source Lucene artifact as a .tgz file."
+
+ inputs.property("git-revision", gitRev)
+
+ outputs.file sourceTgzFile
+
+ doFirst {
+ quietExec {
+ executable = project.externalTool("git")
+ workingDir = project.rootDir
+
+ // An explicit GIT_DIR to prevent .git upward scanning if something goes wrong.
+ environment("GIT_DIR", dotGitPath.toString())
+
+ args += [
+ "archive",
+ "--format",
+ "tgz",
+ "--prefix",
+ "lucene-${version}/",
+ "--output",
+ sourceTgzFile.get().asFile,
+ "HEAD"
+ ]
+ }
+ }
+})
+
// Prepare the "binary" distribution artifact.
apply from: buildscript.sourceFile.toPath().resolveSibling("binary-release.gradle")
@@ -43,8 +74,15 @@ apply from: buildscript.sourceFile.toPath().resolveSibling("binary-release.gradl
// Configure maven artifact collection to a local build folder (required to collect artifacts for the release).
apply from: buildscript.sourceFile.toPath().resolveSibling("collect-maven-artifacts.gradle")
-// Configure artifact signing.
-apply from: buildscript.sourceFile.toPath().resolveSibling("artifact-signing.gradle")
+// Configure release artifact signing.
+tasks.register("signReleaseArchives", Sign, {
+ dependsOn tasks.assembleBinaryTgz
+ sign tasks.assembleBinaryTgz
+
+ // The source tgz is not an archive task so be explicit about the outputs to sign.
+ dependsOn tasks.assembleSourceTgz
+ sign sourceTgzFile.get().asFile
+})
// Set up the HTML-rendered "changes" distribution artifact by linking to documentation's output.
@@ -58,36 +96,34 @@ dependencies {
// Compute checksums for release archives.
-task computeChecksums(type: buildinfra.checksumClass()) {
+tasks.register("computeChecksums", org.apache.lucene.gradle.Checksum, {
files = objects.fileCollection()
[
- tasks.assembleSourceTgz,
- tasks.assembleBinaryTgz,
+ tasks.assembleSourceTgz,
+ tasks.assembleBinaryTgz,
].each { dep ->
dependsOn dep
files += dep.outputs.files
}
outputDir = file("${buildDir}/checksums")
-}
+})
-task prepareGitRev() {
- dependsOn ":gitStatus"
+tasks.register("prepareGitRev", {
+ Provider<RegularFile> outputFile = project.layout.buildDirectory.file(".gitrev")
- ext.outputFile = file("${buildDir}/.gitrev")
-
- outputs.file(ext.outputFile)
- inputs.property("gitrev", provider { -> rootProject.ext.gitRev })
+ inputs.property("gitrev", gitRev)
+ outputs.file(outputFile)
doFirst {
- Files.writeString(ext.outputFile.toPath(), rootProject.ext.gitRev, StandardCharsets.UTF_8)
+ Files.writeString(outputFile.get().asFile.toPath(), gitRev.get(), StandardCharsets.UTF_8)
}
-}
+})
// Assemble everything needed in the release folder structure.
-task assembleRelease(type: Sync) {
+tasks.register("assembleRelease", Sync, {
description "Assemble all Lucene artifacts for a release."
from(configurations.changesHtml, {
@@ -110,15 +146,17 @@ task assembleRelease(type: Sync) {
}
into releaseDir
-}
+})
// Add the description and task group to some of the tasks that make
// sense at the user-level help.
-tasks.matching {it.name in [
+tasks.matching {
+ it.name in [
"assembleSourceTgz",
"assembleBinaryTgz",
"assembleRelease",
-]}.all {
- group "distribution"
+ ]
+}.configureEach {
+ group = "distribution"
}
diff --git a/lucene/distribution/collect-maven-artifacts.gradle b/lucene/distribution/collect-maven-artifacts.gradle
index 4521c25b34a..16dde08c872 100644
--- a/lucene/distribution/collect-maven-artifacts.gradle
+++ b/lucene/distribution/collect-maven-artifacts.gradle
@@ -39,18 +39,18 @@ configure(project(":lucene:distribution")) {
}
}
- def cleanBuildTask = task cleanMavenBuildRepository(type: Delete) {
+ def cleanBuildTask = tasks.register("cleanMavenBuildRepository", Delete, {
delete mavenRepositoryDir
- }
+ })
configure(rootProject.ext.mavenProjects) { Project project ->
// Clean the build repository prior to publishing anything. Ensures we don't
// have multiple artifacts there.
- tasks.matching { it.name ==~ /publish.+ToBuildRepository/ }.all {
+ tasks.matching { it.name ==~ /publish.+ToBuildRepository/ }.configureEach {
dependsOn cleanBuildTask
}
- plugins.withType(PublishingPlugin) {
+ plugins.withType(PublishingPlugin).configureEach {
publishing {
repositories {
maven {
diff --git a/lucene/distribution/source-release.gradle b/lucene/distribution/source-release.gradle
deleted file mode 100644
index fecb435b170..00000000000
--- a/lucene/distribution/source-release.gradle
+++ /dev/null
@@ -1,50 +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.
- */
-
-
-// Prepare the "source" distribution artifact. We use raw git export, no additional complexity needed.
-
-configure(project(":lucene:distribution")) {
- task assembleSourceTgz() {
- description "Assemble source Lucene artifact as a .tgz file."
-
- // Make sure no unstaged/ dirty files are present.
- dependsOn ":gitStatus", ":checkWorkingCopyClean"
-
- ext {
- destination = file("${buildDir}/packages/lucene-${version}-src.tgz")
- }
-
- inputs.property("git-revision", { -> rootProject.ext.gitRev })
- outputs.file destination
-
- doFirst {
- quietExec {
- executable = project.externalTool("git")
- workingDir = project.rootDir
-
- args += [
- "archive",
- "--format", "tgz",
- "--prefix", "lucene-${version}/",
- "--output", destination,
- "HEAD"
- ]
- }
- }
- }
-}
diff --git a/lucene/documentation/src/markdown/index.template.md b/lucene/documentation/src/markdown/index.template.md
index e2db8deb772..456b95f3adc 100644
--- a/lucene/documentation/src/markdown/index.template.md
+++ b/lucene/documentation/src/markdown/index.template.md
@@ -48,8 +48,8 @@ on some of the conceptual or inner details of Lucene:
* [Changes](changes/Changes.html): List of changes in this release.
* [System Requirements](SYSTEM_REQUIREMENTS.html): Minimum and supported Java versions.
-* [Migration Guide](MIGRATE.html): What changed in Lucene ${project.majorVersion()}; how to migrate code from
- Lucene ${project.majorVersion()-1}.x.
+* [Migration Guide](MIGRATE.html): What changed in Lucene ${project.majorVersion}; how to migrate code from
+ Lucene ${project.majorVersion-1}.x.
* [JRE Version Migration](JRE_VERSION_MIGRATION.html): Information about upgrading between major JRE versions.
* [File Formats](core/org/apache/lucene/codecs/${defaultCodecPackage}/package-summary.html#package.description):
Guide to the supported index format used by Lucene. This can be customized by using
diff --git a/lucene/expressions/build.gradle b/lucene/expressions/build.gradle
index cfe7af7cae8..cdb56627c7a 100644
--- a/lucene/expressions/build.gradle
+++ b/lucene/expressions/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Dynamically computed values to sort/facet/search on based on a pluggable grammar'
diff --git a/lucene/facet/build.gradle b/lucene/facet/build.gradle
index ad7dc4bf864..f1a0bc3c6aa 100644
--- a/lucene/facet/build.gradle
+++ b/lucene/facet/build.gradle
@@ -16,7 +16,7 @@
*/
-apply plugin: 'java-library'
+
description = 'Faceted indexing and search capabilities'
diff --git a/lucene/grouping/build.gradle b/lucene/grouping/build.gradle
index 5915c78cccc..b37496b7b2e 100644
--- a/lucene/grouping/build.gradle
+++ b/lucene/grouping/build.gradle
@@ -16,7 +16,7 @@
*/
-apply plugin: 'java-library'
+
description = 'Collectors for grouping search results'
diff --git a/lucene/highlighter/build.gradle b/lucene/highlighter/build.gradle
index d2e7baf391f..ddc06eb51ac 100644
--- a/lucene/highlighter/build.gradle
+++ b/lucene/highlighter/build.gradle
@@ -16,7 +16,7 @@
*/
-apply plugin: 'java-library'
+
description = 'Highlights search keywords in results'
diff --git a/lucene/join/build.gradle b/lucene/join/build.gradle
index 6ed9da28e3d..13000f1aa58 100644
--- a/lucene/join/build.gradle
+++ b/lucene/join/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Index-time and Query-time joins for normalized content'
@@ -23,4 +23,4 @@ dependencies {
moduleApi project(':lucene:core')
moduleTestImplementation project(':lucene:test-framework')
-}
\ No newline at end of file
+}
diff --git a/lucene/luke/build.gradle b/lucene/luke/build.gradle
index 9d1dcdf3907..b85ece891d3 100644
--- a/lucene/luke/build.gradle
+++ b/lucene/luke/build.gradle
@@ -16,8 +16,6 @@
*/
import org.apache.tools.ant.filters.*
-apply plugin: 'java-library'
-
description = 'Luke - Lucene Toolbox'
ext {
@@ -49,14 +47,14 @@ dependencies {
}
// Configure main class name for all JARs.
-tasks.withType(Jar) {
+tasks.withType(Jar).configureEach {
manifest {
attributes("Main-Class": "org.apache.lucene.luke.app.desktop.LukeMain")
}
}
// Configure the main class and version attribute for the module system.
-tasks.compileJava.configure {
+tasks.named("compileJava").configure {
options.javaModuleMainClass.set("org.apache.lucene.luke.app.desktop.LukeMain")
}
@@ -69,10 +67,12 @@ tasks.withType(ProcessResources).configureEach { task ->
}
// Configure "stand-alone" JAR with proper dependency classpath links.
-task standaloneJar(type: Jar) {
+String standaloneJarName = "${project.base.archivesName.get()}-${project.version}-standalone.jar"
+
+tasks.register("standaloneJar", Jar, {
dependsOn classes
- archiveFileName = "${project.base.archivesName.get()}-${project.version}-standalone.jar"
+ archiveFileName = standaloneJarName
from(sourceSets.main.output)
@@ -85,17 +85,12 @@ task standaloneJar(type: Jar) {
}.join(' '))
}
}
-}
+})
-task standaloneAssemble(type: Sync) {
+def standaloneAssembleTask = tasks.register("standaloneAssemble", Sync, {
def antHelper = new org.apache.tools.ant.Project()
- afterEvaluate {
- def substituteProperties = [
- "required.java.version": project.java.targetCompatibility,
- "luke.cmd": "${standaloneJar.archiveFileName.get()}"
- ]
- substituteProperties.each { k, v -> antHelper.setProperty(k.toString(), v.toString()) }
- }
+ antHelper.setProperty("required.java.version", libs.versions.minJava.get())
+ antHelper.setProperty("luke.cmd", standaloneJarName)
from standaloneJar
from configurations.runtimeClasspath
@@ -110,34 +105,38 @@ task standaloneAssemble(type: Sync) {
into standaloneDistDir
doLast {
+
logger.lifecycle(
"""
Standalone Luke distribution assembled. You can run it with:
-java -jar "${standaloneDistDir}/${standaloneJar.archiveFileName.get()}"
+java -jar "${standaloneDistDir}/${standaloneJarName}"
java --module-path "${standaloneDistDir}" -m org.apache.lucene.luke
"""
- )
+ )
}
-}
+})
// Attach standalone distribution assembly to main assembly.
-assemble.dependsOn standaloneAssemble
+tasks.named("assemble").configure {
+ dependsOn standaloneAssembleTask
+}
// Create a standalone package bundle.
-task standalonePackage(type: Tar) {
- from standaloneAssemble
+tasks.register("standalonePackage", Tar, {
+ from standaloneAssembleTask
into "${project.base.archivesName.get()}-${project.version}/"
compression = Compression.GZIP
archiveFileName = "${project.base.archivesName.get()}-${project.version}-standalone.tgz"
-}
+})
// Utility to launch Luke (and fork it from the build).
-task run() {
- dependsOn standaloneAssemble
- description "Launches (spawns) Luke directly from the build process."
- group "Utility launchers"
+tasks.register("run", {
+ description = "Launches (spawns) Luke directly from the build process."
+ group = "Utility launchers"
+
+ dependsOn standaloneAssembleTask
doFirst {
logger.lifecycle("Launching Luke ${project.version} right now...")
@@ -145,10 +144,9 @@ task run() {
executable: rootProject.ext.runtimeJavaExecutable,
spawn: true,
vmlauncher: true
- ) {
- arg(value: '-jar')
- arg(value: file("${standaloneDistDir}/${standaloneJar.archiveFileName.get()}").absolutePath)
- }
+ ) {
+ arg(value: '-jar')
+ arg(value: file("${standaloneDistDir}/${standaloneJar.archiveFileName.get()}").absolutePath)
+ }
}
-}
-
+})
diff --git a/lucene/memory/build.gradle b/lucene/memory/build.gradle
index 789070f6c24..df2c01bb46b 100644
--- a/lucene/memory/build.gradle
+++ b/lucene/memory/build.gradle
@@ -16,7 +16,7 @@
*/
-apply plugin: 'java-library'
+
description = 'Single-document in-memory index implementation'
@@ -25,4 +25,4 @@ dependencies {
moduleTestImplementation project(':lucene:test-framework')
moduleTestImplementation project(':lucene:queryparser')
-}
\ No newline at end of file
+}
diff --git a/lucene/misc/build.gradle b/lucene/misc/build.gradle
index a21dfeaafa7..1f39a53f529 100644
--- a/lucene/misc/build.gradle
+++ b/lucene/misc/build.gradle
@@ -15,11 +15,11 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Index tools and other miscellaneous code'
dependencies {
moduleApi project(':lucene:core')
moduleTestImplementation project(':lucene:test-framework')
-}
\ No newline at end of file
+}
diff --git a/lucene/monitor/build.gradle b/lucene/monitor/build.gradle
index 83d6759c892..3504918162b 100644
--- a/lucene/monitor/build.gradle
+++ b/lucene/monitor/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Reverse-search implementation for monitoring and classification'
diff --git a/lucene/queries/build.gradle b/lucene/queries/build.gradle
index 560365cf54e..1775f54e0c1 100644
--- a/lucene/queries/build.gradle
+++ b/lucene/queries/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Filters and Queries that add to core Lucene'
@@ -25,4 +25,3 @@ dependencies {
moduleTestImplementation project(':lucene:test-framework')
moduleTestImplementation project(':lucene:expressions')
}
-
diff --git a/lucene/queryparser/build.gradle b/lucene/queryparser/build.gradle
index 2390cfe52ca..6e4fdb9443f 100644
--- a/lucene/queryparser/build.gradle
+++ b/lucene/queryparser/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Query parsers and parsing framework'
diff --git a/lucene/queryparser/src/generated/checksums/javaccParserFlexible.json b/lucene/queryparser/src/generated/checksums/javaccParserFlexible.json
index 80081c78b47..db3edc6ac7a 100644
--- a/lucene/queryparser/src/generated/checksums/javaccParserFlexible.json
+++ b/lucene/queryparser/src/generated/checksums/javaccParserFlexible.json
@@ -1,5 +1,5 @@
{
- "lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/ParseException.java": "984cd645fdbad92dd3c8811785e1d48e582bacc5",
+ "lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/ParseException.java": "112c89bfeab0d56b6f9a97b7e2c86a37723d90a8",
"lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/StandardSyntaxParser.java": "dcf92073340d1c38d01905a307f49fc89e094e76",
"lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/StandardSyntaxParser.jj": "77ebf56c78a8614a82532ca6bdf69378afd44b8f",
"lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/StandardSyntaxParserConstants.java": "4ad426d4f4b7577f4af4e9057de32c65c83b1812",
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/ParseException.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/ParseException.java
index e09cc6b696d..27df2a5ab15 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/ParseException.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/parser/ParseException.java
@@ -1,7 +1,7 @@
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 7.0 */
/* JavaCCOptions:KEEP_LINE_COLUMN=true */
package org.apache.lucene.queryparser.flexible.standard.parser;
-
+
import org.apache.lucene.queryparser.flexible.messages.*;
import org.apache.lucene.queryparser.flexible.core.*;
import org.apache.lucene.queryparser.flexible.core.messages.*;
@@ -37,7 +37,7 @@ public class ParseException extends QueryNodeParseException {
* "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException(Token currentTokenVal,
- int[][] expectedTokenSequencesVal, String[] tokenImageVal)
+ int[][] expectedTokenSequencesVal, String[] tokenImageVal)
{
super(new MessageImpl(QueryParserMessages.INVALID_SYNTAX, initialise(
currentTokenVal, expectedTokenSequencesVal, tokenImageVal)));
@@ -57,14 +57,14 @@ public class ParseException extends QueryNodeParseException {
* these constructors.
*/
- public ParseException()
+ public ParseException()
{
super(new MessageImpl(QueryParserMessages.INVALID_SYNTAX, "Error"));
}
/** Constructor with message. */
- public ParseException(Message message)
+ public ParseException(Message message)
{
super(message);
}
diff --git a/lucene/replicator/build.gradle b/lucene/replicator/build.gradle
index abf30ca189c..856bd32671f 100644
--- a/lucene/replicator/build.gradle
+++ b/lucene/replicator/build.gradle
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
-
description = 'Lucene index files replication utility'
dependencies {
@@ -24,4 +22,3 @@ dependencies {
moduleTestImplementation project(':lucene:test-framework')
}
-
diff --git a/lucene/sandbox/build.gradle b/lucene/sandbox/build.gradle
index 72762fe1c3d..daf952f84a8 100644
--- a/lucene/sandbox/build.gradle
+++ b/lucene/sandbox/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Various third party contributions and new ideas'
diff --git a/lucene/spatial-extras/build.gradle b/lucene/spatial-extras/build.gradle
index c2ab9e631cb..b40c270fc13 100644
--- a/lucene/spatial-extras/build.gradle
+++ b/lucene/spatial-extras/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Geospatial search'
@@ -43,4 +43,4 @@ dependencies {
sourceSets.test.extensions.configure("modularPaths", {
it.patchModule("spatial4j", project.providers.provider({ configurations.spatial4jTestPatch.singleFile }))
-})
\ No newline at end of file
+})
diff --git a/lucene/spatial-test-fixtures/build.gradle b/lucene/spatial-test-fixtures/build.gradle
index 983416d8a87..3909a403d70 100644
--- a/lucene/spatial-test-fixtures/build.gradle
+++ b/lucene/spatial-test-fixtures/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = '3D spatial planar geometry test fixtures'
diff --git a/lucene/spatial3d/build.gradle b/lucene/spatial3d/build.gradle
index f7e3618bef5..b140650b85d 100644
--- a/lucene/spatial3d/build.gradle
+++ b/lucene/spatial3d/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = '3D spatial planar geometry APIs'
diff --git a/lucene/suggest/build.gradle b/lucene/suggest/build.gradle
index 25a444d0dbf..51c43ea5667 100644
--- a/lucene/suggest/build.gradle
+++ b/lucene/suggest/build.gradle
@@ -15,13 +15,13 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Auto-suggest and Spellchecking support'
dependencies {
moduleApi project(':lucene:core')
moduleApi project(':lucene:analysis:common')
-
+
moduleTestImplementation project(':lucene:test-framework')
}
diff --git a/lucene/test-framework/build.gradle b/lucene/test-framework/build.gradle
index 7954b1578d7..54128c52427 100644
--- a/lucene/test-framework/build.gradle
+++ b/lucene/test-framework/build.gradle
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-apply plugin: 'java-library'
+
description = 'Framework for testing Lucene-based applications'
diff --git a/settings.gradle b/settings.gradle
index da32f15b939..921a6124c65 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -26,8 +26,8 @@ pluginManagement {
plugins {
id "org.gradle.toolchains.foojay-resolver-convention" version "1.0.0"
- id 'com.gradle.develocity' version '3.19.2'
- id 'com.gradle.common-custom-user-data-gradle-plugin' version '2.3'
+ id 'com.gradle.develocity' version '3.19.2' apply false
+ id 'com.gradle.common-custom-user-data-gradle-plugin' version '2.3' apply false
}
dependencyResolutionManagement {
@@ -38,14 +38,16 @@ dependencyResolutionManagement {
}
}
-if (Boolean.parseBoolean(providers.gradleProperty("gradle.ge").orElse("true").get())) {
- apply from: file('gradle/ge.gradle')
+boolean isCIBuild = System.getenv().keySet().find { it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/ } != null
+boolean enableDevelocity = Boolean.parseBoolean(providers.gradleProperty("gradle.ge").orElse("false").get()) || isCIBuild
+if (enableDevelocity) {
+ apply plugin: "com.gradle.develocity"
+ apply plugin: "com.gradle.common-custom-user-data-gradle-plugin"
+ apply from: file('gradle/develocity.gradle')
}
rootProject.name = "lucene-root"
-includeBuild("build-tools/missing-doclet")
-
include "lucene:analysis:common"
include "lucene:analysis:icu"
include "lucene:analysis:kuromoji"
@@ -86,3 +88,10 @@ include "lucene:spatial-extras"
include "lucene:spatial-test-fixtures"
include "lucene:suggest"
include "lucene:test-framework"
+
+include "lucene:build-tools:missing-doclet"
+include "lucene:build-tools:build-infra-shadow"
+
+// tweak the physical path for build-tools.
+project(":lucene:build-tools:missing-doclet").projectDir = file("build-tools/missing-doclet")
+project(":lucene:build-tools:build-infra-shadow").projectDir = file("build-tools/build-infra-shadow")
diff --git a/versions.lock b/versions.lock
index 3483064f0cd..2a47276b55a 100644
--- a/versions.lock
+++ b/versions.lock
@@ -28,28 +28,28 @@
"test_dependencies" : {
"com.carrotsearch.randomizedtesting:randomizedtesting-runner:2.8.3" : "b35e5d7a,refs=74",
"com.carrotsearch:procfork:1.0.6" : "b7ba1646,refs=2",
- "com.github.ben-manes.caffeine:caffeine:3.0.5" : "6897bc09,refs=38",
- "com.github.kevinstern:software-and-algorithms:1.0" : "6897bc09,refs=38",
- "com.google.auto.service:auto-service-annotations:1.0.1" : "6897bc09,refs=38",
- "com.google.auto.value:auto-value-annotations:1.9" : "6897bc09,refs=38",
- "com.google.auto:auto-common:1.2.2" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_annotation:2.38.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_annotations:2.38.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_check_api:2.38.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_core:2.38.0" : "6897bc09,refs=38",
- "com.google.googlejavaformat:google-java-format:1.24.0" : "6897bc09,refs=38",
- "com.google.guava:failureaccess:1.0.3" : "6897bc09,refs=38",
- "com.google.guava:guava:33.4.6-jre" : "6897bc09,refs=38",
- "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava" : "6897bc09,refs=38",
- "com.google.j2objc:j2objc-annotations:3.0.0" : "6897bc09,refs=38",
- "com.google.protobuf:protobuf-java:3.25.5" : "6897bc09,refs=38",
+ "com.github.ben-manes.caffeine:caffeine:3.0.5" : "7d2143da,refs=39",
+ "com.github.kevinstern:software-and-algorithms:1.0" : "7d2143da,refs=39",
+ "com.google.auto.service:auto-service-annotations:1.0.1" : "7d2143da,refs=39",
+ "com.google.auto.value:auto-value-annotations:1.9" : "7d2143da,refs=39",
+ "com.google.auto:auto-common:1.2.2" : "7d2143da,refs=39",
+ "com.google.errorprone:error_prone_annotation:2.38.0" : "7d2143da,refs=39",
+ "com.google.errorprone:error_prone_annotations:2.38.0" : "7d2143da,refs=39",
+ "com.google.errorprone:error_prone_check_api:2.38.0" : "7d2143da,refs=39",
+ "com.google.errorprone:error_prone_core:2.38.0" : "7d2143da,refs=39",
+ "com.google.googlejavaformat:google-java-format:1.24.0" : "7d2143da,refs=39",
+ "com.google.guava:failureaccess:1.0.3" : "7d2143da,refs=39",
+ "com.google.guava:guava:33.4.6-jre" : "7d2143da,refs=39",
+ "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava" : "7d2143da,refs=39",
+ "com.google.j2objc:j2objc-annotations:3.0.0" : "7d2143da,refs=39",
+ "com.google.protobuf:protobuf-java:3.25.5" : "7d2143da,refs=39",
"com.ibm.icu:icu4j:77.1" : "ffa00415,refs=8",
"commons-codec:commons-codec:1.18.0" : "9dde4cb5,refs=8",
"commons-io:commons-io:2.16.1" : "6f16ff86,refs=2",
- "io.github.eisop:dataflow-errorprone:3.41.0-eisop1" : "6897bc09,refs=38",
- "io.github.java-diff-utils:java-diff-utils:4.12" : "6897bc09,refs=38",
+ "io.github.eisop:dataflow-errorprone:3.41.0-eisop1" : "7d2143da,refs=39",
+ "io.github.java-diff-utils:java-diff-utils:4.12" : "7d2143da,refs=39",
"io.sgr:s2-geometry-library-java:1.0.0" : "1d5a4b2b,refs=4",
- "javax.inject:javax.inject:1" : "6897bc09,refs=38",
+ "javax.inject:javax.inject:1" : "7d2143da,refs=39",
"junit:junit:4.13.2" : "b35e5d7a,refs=74",
"net.bytebuddy:byte-buddy:1.15.11" : "b7ba1646,refs=2",
"net.sf.jopt-simple:jopt-simple:5.0.4" : "152d9f78,refs=3",
@@ -63,14 +63,14 @@
"org.carrot2:morfologik-fsa:2.1.9" : "e077a675,refs=8",
"org.carrot2:morfologik-polish:2.1.9" : "cb00cecf,refs=5",
"org.carrot2:morfologik-stemming:2.1.9" : "e077a675,refs=8",
- "org.checkerframework:checker-qual:3.19.0" : "6897bc09,refs=38",
+ "org.checkerframework:checker-qual:3.19.0" : "7d2143da,refs=39",
"org.hamcrest:hamcrest:3.0" : "b35e5d7a,refs=74",
- "org.jspecify:jspecify:1.0.0" : "6897bc09,refs=38",
+ "org.jspecify:jspecify:1.0.0" : "7d2143da,refs=39",
"org.locationtech.jts:jts-core:1.20.0" : "180518e6,refs=2",
"org.locationtech.spatial4j:spatial4j:0.8" : "1d5a4b2b,refs=4",
"org.openjdk.jmh:jmh-core:1.37" : "152d9f78,refs=3",
"org.openjdk.jmh:jmh-generator-annprocess:1.37" : "ecaf1d73,refs=1",
- "org.pcollections:pcollections:4.0.1" : "6897bc09,refs=38",
+ "org.pcollections:pcollections:4.0.1" : "7d2143da,refs=39",
"org.slf4j:slf4j-api:2.0.17" : "b91715f0,refs=6",
"ua.net.nlp:morfologik-ukrainian-search:4.9.1" : "cb00cecf,refs=5",
"xerces:xercesImpl:2.12.2" : "6f16ff86,refs=2"
@@ -173,7 +173,57 @@
"projectPath" : ":lucene:benchmark"
}
],
- "6897bc09" : [
+ "6f16ff86" : [
+ {
+ "configuration" : "testCompileClasspath",
+ "projectPath" : ":lucene:benchmark"
+ },
+ {
+ "configuration" : "testRuntimeClasspath",
+ "projectPath" : ":lucene:benchmark"
+ }
+ ],
+ "6fbc4021" : [
+ {
+ "configuration" : "testRuntimeClasspath",
+ "projectPath" : ":lucene:benchmark-jmh"
+ },
+ {
+ "configuration" : "testRuntimeClasspath",
+ "projectPath" : ":lucene:demo"
+ },
+ {
+ "configuration" : "testCompileClasspath",
+ "projectPath" : ":lucene:expressions"
+ },
+ {
+ "configuration" : "testRuntimeClasspath",
+ "projectPath" : ":lucene:expressions"
+ },
+ {
+ "configuration" : "testRuntimeClasspath",
+ "projectPath" : ":lucene:queries"
+ }
+ ],
+ "79af844b" : [
+ {
+ "configuration" : "compileClasspath",
+ "projectPath" : ":lucene:luke"
+ },
+ {
+ "configuration" : "runtimeClasspath",
+ "projectPath" : ":lucene:luke"
+ },
+ {
+ "configuration" : "compileClasspath",
+ "projectPath" : ":lucene:analysis:morfologik"
+ },
+ {
+ "configuration" : "runtimeClasspath",
+ "projectPath" : ":lucene:analysis:morfologik"
+ }
+ ],
+ "7d2143da" : [
{
"configuration" : "annotationProcessor",
"projectPath" : ":lucene:analysis.tests"
@@ -325,56 +375,10 @@
{
"configuration" : "annotationProcessor",
"projectPath" : ":lucene:analysis:stempel"
- }
- ],
- "6f16ff86" : [
- {
- "configuration" : "testCompileClasspath",
- "projectPath" : ":lucene:benchmark"
},
{
- "configuration" : "testRuntimeClasspath",
- "projectPath" : ":lucene:benchmark"
- }
- ],
- "6fbc4021" : [
- {
- "configuration" : "testRuntimeClasspath",
- "projectPath" : ":lucene:benchmark-jmh"
- },
- {
- "configuration" : "testRuntimeClasspath",
- "projectPath" : ":lucene:demo"
- },
- {
- "configuration" : "testCompileClasspath",
- "projectPath" : ":lucene:expressions"
- },
- {
- "configuration" : "testRuntimeClasspath",
- "projectPath" : ":lucene:expressions"
- },
- {
- "configuration" : "testRuntimeClasspath",
- "projectPath" : ":lucene:queries"
- }
- ],
- "79af844b" : [
- {
- "configuration" : "compileClasspath",
- "projectPath" : ":lucene:luke"
- },
- {
- "configuration" : "runtimeClasspath",
- "projectPath" : ":lucene:luke"
- },
- {
- "configuration" : "compileClasspath",
- "projectPath" : ":lucene:analysis:morfologik"
- },
- {
- "configuration" : "runtimeClasspath",
- "projectPath" : ":lucene:analysis:morfologik"
+ "configuration" : "annotationProcessor",
+ "projectPath" : ":lucene:build-tools:missing-doclet"
}
],
"85a1e4c6" : [