Skip to content

Apache Lucene open-source search software

Gradle plugins to java, batch 1 (#14862)

Dawid Weissa7fc3d0ae831
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
index 05c3c4ef535..8706cf1931c 100644
--- a/build-tools/build-infra/src/main/groovy/lucene.ide.eclipse.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.ide.eclipse.gradle
@@ -48,7 +48,10 @@ if (gradle.startParameter.taskNames.contains("eclipse")) {
plusConfigurations += allprojects.findAll{ prj ->
return prj.plugins.hasPlugin(JavaPlugin)
}.collectMany {
- return [ it.configurations.compileClasspath, it.configurations.testCompileClasspath ]
+ return [
+ it.configurations.compileClasspath,
+ it.configurations.testCompileClasspath
+ ]
}
file {
@@ -139,4 +142,3 @@ if (gradle.startParameter.taskNames.contains("eclipse")) {
inputs.property('eclipseJavaVersion', eclipseJavaVersion as String)
}
}
-
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle b/build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle
index 955a4bb7501..d99daa91f6f 100644
--- a/build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.java-projects.conventions.gradle
@@ -15,20 +15,26 @@
* limitations under the License.
*/
+import org.apache.lucene.gradle.plugins.spotless.GoogleJavaFormatPlugin
+import org.apache.lucene.gradle.plugins.java.JavaFolderLayoutPlugin
+import org.apache.lucene.gradle.plugins.java.JavacConfigurationPlugin
+import org.apache.lucene.gradle.plugins.java.JarManifestConfigurationPlugin
+
allprojects { project ->
if (['src/java', 'src/test'].any {path ->
project.file(path).exists()
}) {
plugins.apply("java-library")
- plugins.apply("lucene.java.folder-layout")
- plugins.apply("lucene.java.javac")
- plugins.apply("lucene.java.jar-manifest")
+ plugins.apply(JavaFolderLayoutPlugin)
+ plugins.apply(JavacConfigurationPlugin)
+ plugins.apply(JarManifestConfigurationPlugin)
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")
+ plugins.apply(GoogleJavaFormatPlugin)
}
}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.folder-layout.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.folder-layout.gradle
deleted file mode 100644
index 81020aa6b1f..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.java.folder-layout.gradle
+++ /dev/null
@@ -1,45 +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.
- */
-
-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 (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
deleted file mode 100644
index b35504731f6..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.java.jar-manifest.gradle
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.lucene.gradle.plugins.gitinfo.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 javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension)
- 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" : "${-> javaPluginExtension.getSourceCompatibility().toString() }",
- "X-Compile-Target-JDK" : "${-> javaPluginExtension.getTargetCompatibility().toString() }",
-
- "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
deleted file mode 100644
index 8f20d9c030b..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.java.javac.gradle
+++ /dev/null
@@ -1,88 +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 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/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
index ebbbf739b80..1b0ef262dbe 100644
--- 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
@@ -89,7 +89,7 @@ if (project != project.rootProject) {
buildOptions.addOption("tests.seed", "The \"root\" randomization seed for options and test parameters.",
rootProject.getExtensions().getByType(BuildOptionsExtension).getOption("tests.seed").asStringProvider())
}
-optionsInheritedAsProperties += [ "tests.seed" ]
+optionsInheritedAsProperties += ["tests.seed"]
buildOptions.addIntOption("tests.iters", "Duplicate (re-run) each test case N times.")
optionsInheritedAsProperties += ["tests.iters"]
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
index be26a40ee09..bf63ca8d5f5 100644
--- 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
@@ -20,6 +20,7 @@ import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsPlugin
import org.apache.lucene.gradle.plugins.gitinfo.GitInfoPlugin
import org.apache.lucene.gradle.plugins.astgrep.AstGrepPlugin
import org.apache.lucene.gradle.plugins.eclint.EditorConfigLintPlugin
+import org.apache.lucene.gradle.plugins.globals.RegisterBuildGlobalsPlugin
import com.carrotsearch.randomizedtesting.SeedUtils
import java.time.ZonedDateTime
@@ -42,60 +43,26 @@ plugins.apply(BasePlugin)
plugins.apply(GitInfoPlugin)
plugins.apply(AstGrepPlugin)
plugins.apply(EditorConfigLintPlugin)
-
-//
-// 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
+plugins.apply(RegisterBuildGlobalsPlugin)
//
// Expose parts of the final project version to the build. We can't use Runtime.Version, sadly.
//
+def buildGlobals = rootProject.extensions.getByName("buildGlobals")
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
+ // TODO: remove ext properties in favor of using the global extension directly in Java plugins code (typed refs).
+ baseVersion = buildGlobals.baseVersion
+ majorVersion = buildGlobals.majorVersion
+ snapshotBuild = buildGlobals.snapshotBuild
+ isCIBuild = buildGlobals.isCIBuild
// 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)
+ buildDate = buildGlobals.buildDate
+ buildTime = buildGlobals.buildTime
+ buildYear = buildGlobals.buildYear
}
//
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.google-java-format.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.google-java-format.gradle
deleted file mode 100644
index 655d2e2b90a..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.validation.google-java-format.gradle
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.lucene.gradle.plugins.spotless.ApplyGoogleJavaFormatTask
-import org.apache.lucene.gradle.plugins.spotless.CheckGoogleJavaFormatTask
-
-/*
- * This adds automatic (and enforced) code formatting using
- * google-java-format (LUCENE-9564, GITHUB-14824).
- */
-configure(allprojects) {prj ->
- Provider<Integer> batchSizeOption = buildOptions.addIntOption(
- "lucene.gjf.batchSize", "Sets the batch size for google-java-format tasks.", 5)
-
- plugins.withType(JavaPlugin).configureEach {
- def applyGoogleJavaFormat = tasks.register("applyGoogleJavaFormat", ApplyGoogleJavaFormatTask)
-
- def checkGoogleJavaFormat = tasks.register("checkGoogleJavaFormat", CheckGoogleJavaFormatTask, {
- colorizedOutput = !rootProject.ext.isCIBuild
- mustRunAfter applyGoogleJavaFormat
- })
-
- [
- checkGoogleJavaFormat,
- applyGoogleJavaFormat
- ].each {
- it.configure {
- batchSize.set(batchSizeOption)
-
- if (project.path == ":lucene:build-tools:build-infra-shadow") {
- sourceFiles = rootProject.fileTree("build-tools/build-infra/src", {
- include "**/*.java"
- })
- } else {
- sourceFiles = project.fileTree("src", {
- include "**/*.java"
-
- switch (prj.path) {
- case ":lucene:core":
- exclude("**/StandardTokenizerImpl.java")
- break
-
- case ":lucene:analysis:common":
- exclude("**/HTMLStripCharFilter.java",
- "**/UAX29URLEmailTokenizerImpl.java")
- break
-
- case ":lucene:test-framework":
- exclude("**/EmojiTokenizationTestUnicode_11_0.java",
- "**/WordBreakTestUnicode_9_0_0.java")
- break
-
- case ":lucene:queryparser":
- exclude("**/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
- }
- })
- }
- }
- }
-
- // Connect to check and tidy tasks.
- tasks.named("tidy").configure {v ->
- v.dependsOn applyGoogleJavaFormat
- }
-
- tasks.named("check").configure {v ->
- v.dependsOn checkGoogleJavaFormat
- }
- }
-}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.java
new file mode 100644
index 00000000000..3a04c20d16b
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins;
+
+import java.nio.file.Path;
+import java.util.Locale;
+import org.gradle.api.GradleException;
+import org.gradle.api.Plugin;
+import org.gradle.api.Project;
+import org.gradle.api.artifacts.VersionCatalog;
+import org.gradle.api.artifacts.VersionCatalogsExtension;
+
+/** Some common scaffolding and utilities for Lucene gradle plugins. */
+public abstract class LuceneGradlePlugin implements Plugin<Project> {
+ /** Return the version catalog used in the project. */
+ protected static VersionCatalog getVersionCatalog(Project project) {
+ var versionCatalogExt =
+ project.getRootProject().getExtensions().getByType(VersionCatalogsExtension.class);
+ return versionCatalogExt.named("libs");
+ }
+
+ /**
+ * Ensure that {@code project} already has plugin {@code clazz} applied, throw an exception
+ * otherwise.
+ */
+ protected <T extends Plugin<?>> void requiresAppliedPlugin(Project project, Class<T> clazz) {
+ var plugin = project.getPlugins().findPlugin(clazz);
+ if (plugin == null) {
+ throw new GradleException(
+ String.format(
+ Locale.ROOT,
+ "Gradle plugin '%s' requires plugin '%s' to be already applied to project: %s",
+ getClass().getSimpleName(),
+ clazz.getSimpleName(),
+ project.getPath()));
+ }
+ }
+
+ /** Return the main Lucene project path (root path of the repository checkout). */
+ protected static Path getProjectRootPath(Project project) {
+ return project.getLayout().getSettingsDirectory().getAsFile().toPath();
+ }
+
+ /** Ensure the plugin is applied to the root project only, not subprojects. */
+ protected void applicableToRootProjectOnly(Project project) {
+ if (project != project.getRootProject()) {
+ throw new GradleException(
+ "This plugin is applicable to the rootProject only: " + getClass().getSimpleName());
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/gitinfo/GitInfoPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/gitinfo/GitInfoPlugin.java
index 7c580c6b6b7..1d66a83eff0 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/gitinfo/GitInfoPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/gitinfo/GitInfoPlugin.java
@@ -18,17 +18,15 @@ package org.apache.lucene.gradle.plugins.gitinfo;
import java.nio.file.Files;
import java.nio.file.Path;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
import org.gradle.api.GradleException;
-import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.Directory;
-public class GitInfoPlugin implements Plugin<Project> {
+public class GitInfoPlugin extends LuceneGradlePlugin {
@Override
public void apply(Project project) {
- if (project != project.getRootProject()) {
- throw new GradleException("This plugin is applicable to the rootProject only.");
- }
+ applicableToRootProjectOnly(project);
var gitInfoProvider =
project
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/globals/LuceneBuildGlobalsExtension.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/globals/LuceneBuildGlobalsExtension.java
new file mode 100644
index 00000000000..f4d8510becc
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/globals/LuceneBuildGlobalsExtension.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.globals;
+
+/** Global build constants. */
+public abstract class LuceneBuildGlobalsExtension {
+ public static final String NAME = "buildGlobals";
+
+ /** Base Lucene version ({@code x.y.z}). */
+ public String baseVersion;
+
+ /** Major Lucene version ({@code x} in {@code x.y.z}). */
+ public String majorVersion;
+
+ /** {@code true} if this build is a snapshot build. */
+ public boolean snapshotBuild;
+
+ /** Build date ({@code yyyy-MM-dd}. */
+ public String buildDate;
+
+ /** Build time ({@code HH:mm:ss}. */
+ public String buildTime;
+
+ /** Build year ({@code yyyy}. */
+ public String buildYear;
+
+ /**
+ * {@code true} if this build runs on a CI server. This is a heuristic looking for typical env.
+ * variables:
+ *
+ * <ul>
+ * <li>{@code CI}: <a
+ * href="https://docs.github.com/en/actions/learn-github-actions/environment-variables">Github</a>
+ * <li>{@code JENKINS_} or {@code HUDSON_}: <a
+ * href="https://jenkins.thetaphi.de/env-vars.html/">Jenkins/Hudson</a>
+ * </ul>
+ */
+ public boolean isCIBuild;
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/globals/RegisterBuildGlobalsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/globals/RegisterBuildGlobalsPlugin.java
new file mode 100644
index 00000000000..9c6e35ed23f
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/globals/RegisterBuildGlobalsPlugin.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.globals;
+
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsExtension;
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsPlugin;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.GradleException;
+import org.gradle.api.Project;
+import org.gradle.api.provider.Provider;
+
+/** Registers global build constants and extensions. */
+public class RegisterBuildGlobalsPlugin extends LuceneGradlePlugin {
+ private static Pattern VERSION_PATTERN =
+ Pattern.compile("^(?<baseVersion>(?<majorVersion>\\d+)\\.\\d+\\.\\d+)(-(.+))?");
+
+ @Override
+ public void apply(Project project) {
+ applicableToRootProjectOnly(project);
+ requiresAppliedPlugin(project, BuildOptionsPlugin.class);
+
+ String luceneVersion = getLuceneVersion(project);
+ project.setVersion(luceneVersion);
+
+ var tstamp = ZonedDateTime.now();
+ String buildDate = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(tstamp);
+ String buildTime = DateTimeFormatter.ofPattern("HH:mm:ss").format(tstamp);
+ String buildYear = DateTimeFormatter.ofPattern("yyyy").format(tstamp);
+
+ String baseVersion = getBaseVersion(luceneVersion);
+ String majorVersion = getMajorVersion(luceneVersion);
+
+ boolean isCIBuild =
+ System.getenv().keySet().stream()
+ .anyMatch(key -> key.matches("(?i)((JENKINS|HUDSON)(_\\w+)?|CI)"));
+
+ project.allprojects(
+ p -> {
+ var globals =
+ p.getExtensions()
+ .create(LuceneBuildGlobalsExtension.NAME, LuceneBuildGlobalsExtension.class);
+ globals.baseVersion = baseVersion;
+ globals.majorVersion = majorVersion;
+ globals.snapshotBuild = luceneVersion.contains("SNAPSHOT");
+ globals.buildDate = buildDate;
+ globals.buildTime = buildTime;
+ globals.buildYear = buildYear;
+ globals.isCIBuild = isCIBuild;
+ });
+ }
+
+ /** The "major" version in semantic versioning scheme. */
+ private String getMajorVersion(String luceneVersion) {
+ return parseVersion(luceneVersion).group("majorVersion");
+ }
+
+ /**
+ * The "base" version is stripped of the qualifier. Compute it because somebody might have passed
+ * -Pversion.release=x.y.z directly.
+ */
+ private String getBaseVersion(String luceneVersion) {
+ return parseVersion(luceneVersion).group("baseVersion");
+ }
+
+ private static Matcher parseVersion(String luceneVersion) {
+ var matcher = VERSION_PATTERN.matcher(luceneVersion);
+ if (!matcher.matches()) {
+ throw new GradleException("Can't strip version to just x.y.z: " + luceneVersion);
+ }
+ return matcher;
+ }
+
+ /**
+ * Figure out project version strings based on "version.base" and "version.suffix" properties or
+ * use "version.release" if provided explicitly.
+ */
+ private static String getLuceneVersion(Project project) {
+ var buildOptions = project.getExtensions().getByType(BuildOptionsExtension.class);
+ 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();
+ return luceneVersion;
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JarManifestConfigurationPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JarManifestConfigurationPlugin.java
new file mode 100644
index 00000000000..654e00d2448
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JarManifestConfigurationPlugin.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.java;
+
+import java.nio.file.Path;
+import java.util.LinkedHashMap;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.apache.lucene.gradle.plugins.gitinfo.GitInfoExtension;
+import org.apache.lucene.gradle.plugins.globals.LuceneBuildGlobalsExtension;
+import org.gradle.api.Project;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.plugins.JavaPluginExtension;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.tasks.bundling.Jar;
+import org.jetbrains.annotations.NotNull;
+
+/** Sets up the Jar task in gradle: manifest attributes, extra META-INF files, etc. */
+public class JarManifestConfigurationPlugin extends LuceneGradlePlugin {
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+ Project rootProject = project.getRootProject();
+
+ Path legaleseDir = getProjectRootPath(project);
+
+ Provider<String> gitRevProvider =
+ rootProject
+ .getExtensions()
+ .getByType(GitInfoExtension.class)
+ .getGitInfo()
+ .getting("git.commit")
+ .orElse("-");
+
+ // Declare these inline for now. Don't know if it makes sense to declare them
+ // per-project.
+ var title = "Lucene Search Engine: " + project.getName();
+ var implementationTitle = "org.apache.lucene";
+
+ var globals = rootProject.getExtensions().getByType(LuceneBuildGlobalsExtension.class);
+
+ // Apply the manifest to any JAR or WAR file created by any project.
+ project
+ .getTasks()
+ .withType(Jar.class)
+ .configureEach(
+ task -> {
+ task.getInputs().property("gitRev", gitRevProvider);
+
+ var attributes = new LinkedHashMap<String, Object>();
+
+ attributes.put("Extension-Name", implementationTitle);
+ attributes.put("Implementation-Vendor", "The Apache Software Foundation");
+ attributes.put("Implementation-Title", implementationTitle);
+ attributes.put(
+ "Implementation-Version",
+ getImplementationVersion(project, gitRevProvider.get(), globals));
+
+ // 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.
+ attributes.put("Specification-Vendor", "The Apache Software Foundation");
+ attributes.put("Specification-Version", globals.baseVersion);
+ attributes.put("Specification-Title", title);
+
+ var javaPluginExtension =
+ project.getExtensions().getByType(JavaPluginExtension.class);
+ attributes.put(
+ "X-Compile-Source-JDK", javaPluginExtension.getSourceCompatibility().toString());
+ attributes.put(
+ "X-Compile-Target-JDK", javaPluginExtension.getTargetCompatibility().toString());
+
+ attributes.put(
+ "X-Build-JDK",
+ System.getProperty("java.version")
+ + " ("
+ + System.getProperty("java.vendor")
+ + " "
+ + System.getProperty("java.vm.version")
+ + ")");
+ attributes.put(
+ "X-Build-OS",
+ System.getProperty("os.name")
+ + " "
+ + System.getProperty("os.arch")
+ + " "
+ + System.getProperty("os.version"));
+
+ task.getManifest().attributes(attributes);
+
+ // Copy legalese into META-INF.
+ task.getMetaInf()
+ .from(
+ legaleseDir.toFile(),
+ spec -> {
+ spec.include("LICENSE.txt", "NOTICE.txt");
+ });
+ });
+ }
+
+ private static @NotNull String getImplementationVersion(
+ Project project, String gitRev, LuceneBuildGlobalsExtension globals) {
+ if (globals.snapshotBuild) {
+ return project.getVersion() + " " + gitRev + " [snapshot build, details omitted]";
+ } else {
+ return project.getVersion()
+ + (" " + gitRev)
+ + (" - " + globals.buildDate)
+ + (" " + globals.buildTime);
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaFolderLayoutPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaFolderLayoutPlugin.java
new file mode 100644
index 00000000000..fd0e5d726a8
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaFolderLayoutPlugin.java
@@ -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.
+ */
+package org.apache.lucene.gradle.plugins.java;
+
+import java.io.File;
+import java.util.List;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.Project;
+import org.gradle.api.artifacts.ConfigurationContainer;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.plugins.JavaPluginExtension;
+import org.gradle.api.tasks.SourceSet;
+import org.gradle.api.tasks.SourceSetContainer;
+import org.gradle.language.jvm.tasks.ProcessResources;
+
+/** Configure up non-standard, legacy folder structure in Lucene projects. */
+public class JavaFolderLayoutPlugin extends LuceneGradlePlugin {
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+
+ JavaPluginExtension javaExt = project.getExtensions().getByType(JavaPluginExtension.class);
+ SourceSetContainer sourceSets = javaExt.getSourceSets();
+
+ SourceSet mainSrcSet = sourceSets.named("main").get();
+ mainSrcSet.java(srcSetDir -> srcSetDir.setSrcDirs(List.of("src/java")));
+ mainSrcSet.resources(resources -> resources.setSrcDirs(List.of("src/resources")));
+
+ SourceSet testSrcSet = sourceSets.named("test").get();
+ testSrcSet.java(srcSetDir -> srcSetDir.setSrcDirs(List.of("src/test")));
+ testSrcSet.resources(resources -> resources.setSrcDirs(List.of("src/test-files")));
+
+ project
+ .getTasks()
+ .withType(ProcessResources.class)
+ .named("processTestResources")
+ .configure(
+ task -> {
+ task.from("src/test").exclude("**/*.java");
+ });
+
+ // if 'src/tools' exists, add it as a separate sourceSet.
+ File toolsSrc = project.file("src/tools/java");
+ if (toolsSrc.exists()) {
+ sourceSets
+ .create("tools")
+ .java(
+ srcSet -> {
+ srcSet.setSrcDirs(List.of(toolsSrc));
+ });
+
+ // and inherit any dependencies for this source set from the main source set.
+ ConfigurationContainer configurations = project.getConfigurations();
+ configurations
+ .named("toolsImplementation")
+ .configure(
+ conf -> {
+ conf.extendsFrom(configurations.named("implementation").get());
+ });
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavacConfigurationPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavacConfigurationPlugin.java
new file mode 100644
index 00000000000..72276d3b018
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavacConfigurationPlugin.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.java;
+
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsExtension;
+import java.util.List;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.JavaVersion;
+import org.gradle.api.Project;
+import org.gradle.api.artifacts.VersionCatalog;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.plugins.JavaPluginExtension;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.tasks.compile.CompileOptions;
+import org.gradle.api.tasks.compile.JavaCompile;
+
+/** Sets up various JavaCompile task options. */
+public class JavacConfigurationPlugin extends LuceneGradlePlugin {
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+
+ VersionCatalog versionCatalog = getVersionCatalog(project);
+ JavaVersion minJavaVersion = JavaVersion.toVersion(versionCatalog.findVersion("minJava").get());
+
+ BuildOptionsExtension buildOptions =
+ project.getExtensions().getByType(BuildOptionsExtension.class);
+ Provider<Boolean> failOnWarningsOption =
+ buildOptions.addBooleanOption(
+ "javac.failOnWarnings", "Triggers failures on javac warnings.", true);
+
+ JavaPluginExtension javaExtension =
+ project.getExtensions().getByType(JavaPluginExtension.class);
+ javaExtension.setSourceCompatibility(minJavaVersion);
+ javaExtension.setTargetCompatibility(minJavaVersion);
+
+ project
+ .getTasks()
+ .withType(JavaCompile.class)
+ .configureEach(
+ task -> {
+ CompileOptions options = task.getOptions();
+
+ // Use 'release' flag instead of 'source' and 'target'
+ options.getCompilerArgs().addAll(List.of("--release", minJavaVersion.toString()));
+
+ options.setEncoding("UTF-8");
+
+ // Configure warnings. Use 'javac --help-lint' to get the supported list
+ options
+ .getCompilerArgs()
+ .addAll(
+ List.of(
+ "-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.getPath().equals(":lucene:benchmark-jmh")) {
+ // Ignore, JMH benchmarks use JMH preprocessor and incubating modules.
+ } else {
+ // proc:none was added because of LOG4J2-1925 / JDK-8186647
+ options.getCompilerArgs().add("-proc:none");
+
+ if (failOnWarningsOption.get()) {
+ options.getCompilerArgs().add("-Werror");
+ }
+ }
+ });
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ApplyGoogleJavaFormatTask.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ApplyGoogleJavaFormatTask.java
index c7a8434afd0..c7d9440f942 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ApplyGoogleJavaFormatTask.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ApplyGoogleJavaFormatTask.java
@@ -44,6 +44,7 @@ public abstract class ApplyGoogleJavaFormatTask extends ParentGoogleJavaFormatTa
public void formatSources(InputChanges inputChanges) throws IOException {
WorkQueue workQueue = getWorkQueue();
List<File> sourceFiles = getIncrementalBatch(inputChanges);
+
if (sourceFiles.isEmpty()) {
return;
}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/GoogleJavaFormatPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/GoogleJavaFormatPlugin.java
new file mode 100644
index 00000000000..4c4ca6cd824
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/GoogleJavaFormatPlugin.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.spotless;
+
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsExtension;
+import java.util.List;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.Project;
+import org.gradle.api.file.ConfigurableFileTree;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.tasks.TaskContainer;
+import org.gradle.api.tasks.TaskProvider;
+
+/**
+ * This adds automatic (and enforced) code formatting using google-java-format (LUCENE-9564,
+ * GITHUB-14824).
+ */
+public class GoogleJavaFormatPlugin extends LuceneGradlePlugin {
+ private static final int DEFAULT_BATCH_SIZE = 5;
+ private static final String GJF_BATCH_SIZE_OPTION = "lucene.gjf.batchSize";
+
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+
+ TaskContainer tasks = project.getTasks();
+
+ TaskProvider<ApplyGoogleJavaFormatTask> applyTask =
+ tasks.register("applyGoogleJavaFormat", ApplyGoogleJavaFormatTask.class);
+
+ TaskProvider<CheckGoogleJavaFormatTask> checkTask =
+ tasks.register(
+ "checkGoogleJavaFormat",
+ CheckGoogleJavaFormatTask.class,
+ task -> {
+ Object isCiBuild = project.getRootProject().findProperty("isCIBuild");
+ task.getColorizedOutput().set(!(isCiBuild instanceof Boolean && (Boolean) isCiBuild));
+ task.mustRunAfter(applyTask);
+ });
+
+ Provider<Integer> batchSizeOption =
+ project
+ .getExtensions()
+ .getByType(BuildOptionsExtension.class)
+ .addIntOption(
+ GJF_BATCH_SIZE_OPTION,
+ "Sets the batch size for google-java-format tasks.",
+ DEFAULT_BATCH_SIZE);
+
+ // Connect to check and tidy tasks.
+ tasks.named("tidy", tidy -> tidy.dependsOn(applyTask));
+ tasks.named("check", check -> check.dependsOn(checkTask));
+
+ // Configure details depending on the project.
+
+ for (var t : List.of(applyTask, checkTask)) {
+ t.configure(
+ task -> {
+ task.getBatchSize().set(batchSizeOption);
+ });
+ }
+
+ for (var t : List.of(applyTask, checkTask)) {
+ t.configure(
+ task -> {
+ var srcTree =
+ project.getPath().equals(":lucene:build-tools:build-infra-shadow")
+ ? project.getRootProject().fileTree("build-tools/build-infra/src")
+ : project.fileTree("src");
+
+ srcTree.include("**/*.java");
+ configureExclusions(project, srcTree);
+
+ task.getSourceFiles().setFrom(srcTree);
+ });
+ }
+ }
+
+ private void configureExclusions(Project project, ConfigurableFileTree ftree) {
+ switch (project.getPath()) {
+ case ":lucene:core":
+ ftree.exclude("**/StandardTokenizerImpl.java");
+ break;
+
+ case ":lucene:analysis:common":
+ ftree.exclude("**/HTMLStripCharFilter.java", "**/UAX29URLEmailTokenizerImpl.java");
+ break;
+
+ case ":lucene:test-framework":
+ ftree.exclude(
+ "**/EmojiTokenizationTestUnicode_11_0.java", "**/WordBreakTestUnicode_9_0_0.java");
+ break;
+
+ case ":lucene:queryparser":
+ ftree.exclude(
+ "**/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;
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ParentGoogleJavaFormatTask.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ParentGoogleJavaFormatTask.java
index 1049111037e..03c6ec98198 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ParentGoogleJavaFormatTask.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ParentGoogleJavaFormatTask.java
@@ -114,6 +114,9 @@ abstract class ParentGoogleJavaFormatTask extends DefaultTask {
input = ImportOrderer.reorderImports(input, JavaFormatterOptions.Style.GOOGLE);
input = RemoveUnusedImports.removeUnusedImports(input);
input = formatter.formatSource(input);
+
+ // input = StringWrapper.wrap(input, formatter);
+
return input;
}
diff --git a/build.gradle b/build.gradle
index 38103a6ad4e..e70d7cc2115 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,3 +1,5 @@
+import org.apache.lucene.gradle.plugins.spotless.GoogleJavaFormatPlugin
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -38,7 +40,6 @@ plugins {
id "lucene.java.modules"
id "lucene.validation.spotless-groovy"
- id "lucene.validation.google-java-format"
id "lucene.validation.lockfile"
id "lucene.validation.gradle-versions-cleanup"
id "lucene.validation.gradlew-scripts-customizations"