Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

Reformat gradle files with IntelliJ / .editorconfig (#4037)

David Smiley92792f735615
diff --git a/build-tools/build-infra/settings.gradle b/build-tools/build-infra/settings.gradle
index 7a55021b366..c03775cb0b9 100644
--- a/build-tools/build-infra/settings.gradle
+++ b/build-tools/build-infra/settings.gradle
@@ -19,9 +19,9 @@ rootProject.name = 'build-infra'
// Use project's version catalog for centralized dependency management
dependencyResolutionManagement {
- versionCatalogs {
- libs {
- from(files("../../gradle/libs.versions.toml"))
- }
+ versionCatalogs {
+ libs {
+ from(files("../../gradle/libs.versions.toml"))
}
+ }
}
diff --git a/build-tools/missing-doclet/settings.gradle b/build-tools/missing-doclet/settings.gradle
index c39219472be..c8abe2fa87f 100644
--- a/build-tools/missing-doclet/settings.gradle
+++ b/build-tools/missing-doclet/settings.gradle
@@ -19,9 +19,9 @@ rootProject.name = "missing-doclet"
// Use project's version catalog for centralized dependency management
dependencyResolutionManagement {
- versionCatalogs {
- libs {
- from(files("../../gradle/libs.versions.toml"))
- }
+ versionCatalogs {
+ libs {
+ from(files("../../gradle/libs.versions.toml"))
}
+ }
}
diff --git a/build.gradle b/build.gradle
index 50a618d6936..fbe24effa4d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -41,7 +41,8 @@ rootProject.ext.minJavaVersionDefault = JavaVersion.toVersion(libs.versions.java
rootProject.ext.minJavaVersionSolrJ = JavaVersion.toVersion(libs.versions.java.solrj.get())
// Check development mode for entire project (defaults to true if 'production' not provided and set to true)
-rootProject.ext.development = !project.hasProperty('production') || project.findProperty('production') != 'true'
+rootProject.ext.development =
+ !project.hasProperty('production') || project.findProperty('production') != 'true'
apply from: file('gradle/globals.gradle')
@@ -54,10 +55,10 @@ version = {
// 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')
String v = propertyOrDefault('version.release', "${baseVersion}-${versionSuffix}")
if (v.endsWith("-")) {
@@ -73,7 +74,7 @@ allprojects {
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
- options.compilerArgs << "-Xmaxerrs" << "1000"
+ options.compilerArgs << "-Xmaxerrs" << "1000"
}
}
}
@@ -105,13 +106,13 @@ ext {
buildYear = DateTimeFormatter.ofPattern("yyyy").format(tstamp)
// Allow definiting external tool locations using system props.
- externalTool = { name ->
+ externalTool = {name ->
def resolved = propertyOrDefault("${name}.exe", name as String)
logger.info("External tool '${name}' resolved to: ${resolved}")
return resolved
}
-
- luceneBaseVersionProvider = project.provider {
+
+ luceneBaseVersionProvider = project.provider {
def luceneVersion = libs.versions.apache.lucene.get()
def m = (luceneVersion =~ /^\d+\.\d+\.\d+\b/)
if (!m) {
@@ -123,7 +124,13 @@ ext {
}
// For testing code
- vectorIncubatorJavaVersions = [ JavaVersion.VERSION_21, JavaVersion.VERSION_22, JavaVersion.VERSION_23, JavaVersion.VERSION_24, JavaVersion.VERSION_25 ] as Set
+ vectorIncubatorJavaVersions = [
+ JavaVersion.VERSION_21,
+ JavaVersion.VERSION_22,
+ JavaVersion.VERSION_23,
+ JavaVersion.VERSION_24,
+ JavaVersion.VERSION_25
+ ] as Set
// Use gradle flag in root project for further referencing
withUiModule = gradle.ext.withUiModule
diff --git a/gradle/conventions.gradle b/gradle/conventions.gradle
index fabc9b4cc58..6a211be3e72 100644
--- a/gradle/conventions.gradle
+++ b/gradle/conventions.gradle
@@ -16,18 +16,18 @@
*/
configure(allprojects) {
- tasks.register("tidy").configure {
- description "Applies formatters and cleanups to sources."
- group "verification"
- }
+ tasks.register("tidy").configure {
+ description "Applies formatters and cleanups to sources."
+ group "verification"
+ }
}
// 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$', ""))
- }
+ ext {
+ scriptResources = {buildscript ->
+ return file(buildscript.sourceFile.absolutePath.replaceAll('.gradle$', ""))
}
+ }
}
diff --git a/gradle/develocity.gradle b/gradle/develocity.gradle
index 33e624597dd..d744f3d8b5e 100644
--- a/gradle/develocity.gradle
+++ b/gradle/develocity.gradle
@@ -16,49 +16,49 @@
*/
// see globals.gradle
-def isCIBuild = System.getenv().keySet().any { it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/ }
+def isCIBuild = System.getenv().keySet().any {it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/}
// https://docs.gradle.com/enterprise/gradle-plugin/
develocity {
- server = "https://develocity.apache.org"
- projectId = "solr"
+ server = "https://develocity.apache.org"
+ projectId = "solr"
- buildScan {
- uploadInBackground = !isCIBuild
+ buildScan {
+ uploadInBackground = !isCIBuild
- publishing.onlyIf { it.authenticated }
- obfuscation {
- ipAddresses { addresses -> addresses.collect { address -> "0.0.0.0"} }
- }
+ publishing.onlyIf {it.authenticated}
+ obfuscation {
+ ipAddresses {addresses -> addresses.collect {address -> "0.0.0.0"}}
+ }
- tag("JDK" + System.getProperty("java.version").find(/\d+/)) // major version
- value("Java Vendor", System.getProperty("java.vendor"))
- value("Java Version", System.getProperty("java.version"))
+ tag("JDK" + System.getProperty("java.version").find(/\d+/)) // major version
+ value("Java Vendor", System.getProperty("java.vendor"))
+ value("Java Version", System.getProperty("java.version"))
- // Jenkins job name, less redundant "Solr" parts
- String jenkinsJobName = System.getenv("JOB_NAME")
- if (jenkinsJobName) { // looks like "Solr/Solr-Smoketest-9.5"
- tag(jenkinsJobName.replaceAll(/Solr\W/,"")) // like "Smoketest-9.5"
- }
+ // Jenkins job name, less redundant "Solr" parts
+ String jenkinsJobName = System.getenv("JOB_NAME")
+ if (jenkinsJobName) { // looks like "Solr/Solr-Smoketest-9.5"
+ tag(jenkinsJobName.replaceAll(/Solr\W/, "")) // like "Smoketest-9.5"
+ }
- // https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables
- if (System.getenv("GITHUB_BASE_REF")) { // only exists for PRs
- tag("PR")
- }
- String ghWorkflowName = System.getenv("GITHUB_WORKFLOW")
- if (ghWorkflowName) {
- tag(ghWorkflowName)
- }
+ // https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables
+ if (System.getenv("GITHUB_BASE_REF")) { // only exists for PRs
+ tag("PR")
+ }
+ String ghWorkflowName = System.getenv("GITHUB_WORKFLOW")
+ if (ghWorkflowName) {
+ tag(ghWorkflowName)
}
+ }
}
buildCache {
- local {
- enabled = !isCIBuild
- }
+ local {
+ enabled = !isCIBuild
+ }
- remote(develocity.buildCache) {
- enabled = false
- }
+ remote(develocity.buildCache) {
+ enabled = false
+ }
}
diff --git a/gradle/documentation/changes-to-html.gradle b/gradle/documentation/changes-to-html.gradle
index 0f21cfca506..72a10624f09 100644
--- a/gradle/documentation/changes-to-html.gradle
+++ b/gradle/documentation/changes-to-html.gradle
@@ -53,7 +53,7 @@ class ChangesToHtmlTask extends DefaultTask {
@OutputDirectory
final DirectoryProperty targetDir = project.objects.directoryProperty()
- .fileProvider(project.providers.provider { project.file("${project.docroot}/changes") })
+ .fileProvider(project.providers.provider {project.file("${project.docroot}/changes")})
@InputFile
def script
@@ -63,8 +63,8 @@ class ChangesToHtmlTask extends DefaultTask {
// Check if Python is available
if (!pythonExists()) {
- logger.warn("WARNING: Python is not installed, skipping creating Changes.html")
- return
+ logger.warn("WARNING: Python is not installed, skipping creating Changes.html")
+ return
}
def result = project.exec {
@@ -101,11 +101,11 @@ class ChangesToHtmlTask extends DefaultTask {
def pythonExists() {
try {
- def process = "python3 --version".execute()
- process.waitFor()
- return process.exitValue() == 0
+ def process = "python3 --version".execute()
+ process.waitFor()
+ return process.exitValue() == 0
} catch (Exception e) {
- return false
+ return false
}
}
}
diff --git a/gradle/documentation/documentation.gradle b/gradle/documentation/documentation.gradle
index 81862df227b..8aa3f4a0bb0 100644
--- a/gradle/documentation/documentation.gradle
+++ b/gradle/documentation/documentation.gradle
@@ -38,7 +38,9 @@ configure(rootProject) {
}
}())
- solrRefguideUrl = project.propertyOrDefault('solr.refguide.url', "https://solr.apache.org/guide/solr/${refguideUrlVersion}")
+ solrRefguideUrl =
+ project.propertyOrDefault('solr.refguide.url',
+ "https://solr.apache.org/guide/solr/${refguideUrlVersion}")
}
task documentation() {
@@ -65,11 +67,11 @@ configure(project(':solr:documentation')) {
group = 'documentation'
description = "Generate ${project.name.capitalize()} documentation"
- dependsOn project.parent.subprojects.collect { prj ->
- prj.tasks.matching { it.name == 'renderSiteJavadoc' }
+ dependsOn project.parent.subprojects.collect {prj ->
+ prj.tasks.matching {it.name == 'renderSiteJavadoc'}
}
- dependsOn 'changesToHtml','copyDocumentationAssets',
- 'markdownToHtml','createDocumentationIndex'
+ dependsOn 'changesToHtml', 'copyDocumentationAssets',
+ 'markdownToHtml', 'createDocumentationIndex'
}
task copyDocumentationAssets(type: Copy) {
@@ -77,7 +79,7 @@ configure(project(':solr:documentation')) {
from(project.assets)
into project.docroot
}
-
+
assemble {
dependsOn documentation
}
@@ -85,7 +87,7 @@ configure(project(':solr:documentation')) {
configurations {
site
}
-
+
artifacts {
site project.docroot, {
builtBy documentation
@@ -95,7 +97,9 @@ configure(project(':solr:documentation')) {
task documentationMinimal() {
group = 'documentation'
description = "Generate stub Solr documentation pointing to web page (that's part of Solr TGZ)"
- dependsOn 'copyMiniDocumentationAssets', 'createMiniDocumentationIndex', 'copyChangesToHtmlForMiniSite'
+ dependsOn 'copyMiniDocumentationAssets',
+ 'createMiniDocumentationIndex',
+ 'copyChangesToHtmlForMiniSite'
}
task copyChangesToHtmlForMiniSite(type: Copy) {
diff --git a/gradle/documentation/markdown.gradle b/gradle/documentation/markdown.gradle
index d9a890d72eb..0506badfe8f 100644
--- a/gradle/documentation/markdown.gradle
+++ b/gradle/documentation/markdown.gradle
@@ -43,7 +43,7 @@ buildscript {
configure(project(':solr:documentation')) {
task markdownToHtml(type: Copy) {
dependsOn copyDocumentationAssets
-
+
filteringCharset = 'UTF-8'
includeEmptyDirs = false
into project.docroot
@@ -93,27 +93,28 @@ 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)');
+
// convert the markdown
MutableDataSet options = new MutableDataSet();
options.setFrom(ParserEmulationProfile.MARKDOWN);
- options.set(Parser.EXTENSIONS, [ AbbreviationExtension.create(), AutolinkExtension.create(), AttributesExtension.create() ]);
+ options.set(Parser.EXTENSIONS,
+ [AbbreviationExtension.create(), AutolinkExtension.create(), AttributesExtension.create()]);
options.set(HtmlRenderer.RENDER_HEADER_ID, true);
options.set(HtmlRenderer.MAX_TRAILING_BLANK_LINES, 0);
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;
@@ -132,21 +133,22 @@ class MarkdownTemplateTask extends DefaultTask {
@OutputFile
File outputFile
-
+
@Input
@Optional
- final MapProperty<String,Object> binding = project.objects.mapProperty(String, Object)
-
+ 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.startsWith('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}"
+ 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.startsWith('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') {
text = text.concat(' {style="font-size:larger; margin-bottom:.5em"}')
}
@@ -159,7 +161,7 @@ class MarkdownTemplateTask extends DefaultTask {
void transform() {
def engine = new SimpleTemplateEngine();
def resolvedBinding = binding.get() + [
- project : project
+ project: project
]
String markdown = templateFile.withReader('UTF-8') {
engine.createTemplate(it).make(resolvedBinding).toString();
diff --git a/gradle/documentation/pull-lucene-javadocs.gradle b/gradle/documentation/pull-lucene-javadocs.gradle
index aa6990ebf8b..d24b763d5fd 100644
--- a/gradle/documentation/pull-lucene-javadocs.gradle
+++ b/gradle/documentation/pull-lucene-javadocs.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// Pull and unpack Lucene javadocs from published Maven artifacts for use in local link checking.
configure(project(":solr:documentation")) {
@@ -45,16 +44,15 @@ configure(project(":solr:documentation")) {
// from all Solr javadocs?) then perhaps we can find a way to build this list programmatically?
// - If these javadocs are only consumed by the ref guide, then these deps & associated tasks
// should just be moved to the ref-guide build.gradle
- javadocs variantOf(libs.apache.lucene.core) { classifier 'javadoc' }
- javadocs variantOf(libs.apache.lucene.expressions) { classifier 'javadoc' }
- javadocs variantOf(libs.apache.lucene.analysis.common) { classifier 'javadoc' }
- javadocs variantOf(libs.apache.lucene.analysis.stempel) { classifier 'javadoc' }
- javadocs variantOf(libs.apache.lucene.queryparser) { classifier 'javadoc' }
- javadocs variantOf(libs.apache.lucene.queries) { classifier 'javadoc' }
- javadocs variantOf(libs.apache.lucene.spatialextras) { classifier 'javadoc' }
+ javadocs variantOf(libs.apache.lucene.core) {classifier 'javadoc'}
+ javadocs variantOf(libs.apache.lucene.expressions) {classifier 'javadoc'}
+ javadocs variantOf(libs.apache.lucene.analysis.common) {classifier 'javadoc'}
+ javadocs variantOf(libs.apache.lucene.analysis.stempel) {classifier 'javadoc'}
+ javadocs variantOf(libs.apache.lucene.queryparser) {classifier 'javadoc'}
+ javadocs variantOf(libs.apache.lucene.queries) {classifier 'javadoc'}
+ javadocs variantOf(libs.apache.lucene.spatialextras) {classifier 'javadoc'}
}
-
task collectLuceneJavadocs() {
description "Collect and unpack javadoc artifacts from 'javadocs' configuration"
@@ -64,15 +62,17 @@ configure(project(":solr:documentation")) {
doFirst {
def resolved = configurations.javadocs.resolvedConfiguration
- resolved.resolvedArtifacts.each { artifact ->
+ resolved.resolvedArtifacts.each {artifact ->
def id = artifact.moduleVersion.id
- // This mimics the directory structure used on lucene.apache.org for the javadocs of all modules.
+ // This mimics the directory structure used on lucene.apache.org for the javadocs of
+ // all modules.
//
- // HACK: the lucene.apache.org javadocs are organized to match the module directory structure in the repo,
- // not the "flat" artifact names -- so there is no one size fits all way to determine the directory name.
- // We have to "special case" that analysis-* modules are in an 'analysis/*' subdir, while the general rule is that
- // '-' in artifact names are left as part of the dir name (ie: 'spatial-extras/')....
- def path = id.name.replaceFirst('^lucene-', '').replaceFirst('^analysis-','analysis/')
+ // HACK: the lucene.apache.org javadocs are organized to match the module directory
+ // structure in the repo, not the "flat" artifact names -- so there is no one size fits
+ // all way to determine the directory name. We have to "special case" that analysis-*
+ // modules are in an 'analysis/*' subdir, while the general rule is that '-' in artifact
+ // names are left as part of the dir name (ie: 'spatial-extras/')....
+ def path = id.name.replaceFirst('^lucene-', '').replaceFirst('^analysis-', 'analysis/')
project.sync {
from zipTree(artifact.file)
into file("${project.ext.luceneDocsDir}/${path}/")
diff --git a/gradle/documentation/render-javadoc.gradle b/gradle/documentation/render-javadoc.gradle
index 6102b39a06d..ff1f140ef60 100644
--- a/gradle/documentation/render-javadoc.gradle
+++ b/gradle/documentation/render-javadoc.gradle
@@ -40,7 +40,7 @@ allprojects {
// 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 {
+ tasks.matching {it.name == "javadoc"}.all {
enabled = false
dependsOn "renderJavadoc"
}
@@ -87,11 +87,12 @@ allprojects {
title = "Solr ${project.version} ${project.name} API"
offlineLinks += [
- "https://docs.oracle.com/en/java/javase/${project.minJavaVersion}/docs/api/": rootProject.file("${resources}/java${project.minJavaVersion}/"),
+ "https://docs.oracle.com/en/java/javase/${project.minJavaVersion}/docs/api/": rootProject
+ .file("${resources}/java${project.minJavaVersion}/"),
"https://junit.org/junit4/javadoc/4.12/": rootProject.file("${resources}/junit/")
]
- solrDocUrl = provider({ rootProject.solrDocUrl })
+ solrDocUrl = provider({rootProject.solrDocUrl})
// Set up custom doclet.
dependsOn configurations.missingdoclet
@@ -136,10 +137,10 @@ configure(project(":solr:solrj-zookeeper")) {
project.tasks.withType(RenderJavadocTask) {
// TODO: clean up split packages SOLR-15604
javadocMissingIgnore = [
- "org.apache.solr.common",
- "org.apache.solr.common.cloud",
- "org.apache.solr.client.solrj.impl",
- "org.apache.solr.client.solrj.cloud"
+ "org.apache.solr.common",
+ "org.apache.solr.common.cloud",
+ "org.apache.solr.client.solrj.impl",
+ "org.apache.solr.client.solrj.cloud"
]
}
}
@@ -190,9 +191,11 @@ configure(subprojects.findAll {
// - each RenderJavaDocs task gets a dependency to all tasks with 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) {task ->
task.dependsOn {
- task.project.configurations.implementation.allDependencies.withType(ProjectDependency).collect { dep ->
+ task
+ .project
+ .configurations.implementation.allDependencies.withType(ProjectDependency).collect {dep ->
def otherProject = dep.dependencyProject
return otherProject.tasks.findByName(task.name)
}.findAll {
@@ -257,7 +260,7 @@ class RenderJavadocTask extends DefaultTask {
// Computes cacheable inputs from the map in offlineLinks.
@Nested
List<OfflineLink> getCacheableOfflineLinks() {
- return offlineLinks.collect { url, location -> new OfflineLink(url, location) }
+ return offlineLinks.collect {url, location -> new OfflineLink(url, location)}
}
@Input
@@ -283,7 +286,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)
@@ -294,13 +297,13 @@ class RenderJavadocTask extends DefaultTask {
private Set findRenderTasksInDependencies() {
Set found = []
def collectDeps
- collectDeps = { task ->
+ collectDeps = {task ->
task.taskDependencies.getDependencies(task)
- .findAll{ it.name == this.name && it.enabled && !found.contains(it) }
- .each{
- found << it
- collectDeps(it)
- }
+ .findAll {it.name == this.name && it.enabled && !found.contains(it)}
+ .each {
+ found << it
+ collectDeps(it)
+ }
}
collectDeps(this)
return found
@@ -308,7 +311,7 @@ class RenderJavadocTask extends DefaultTask {
@TaskAction
public void render() {
- def srcDirs = srcDirSet.srcDirs.findAll { dir -> dir.exists() }
+ def srcDirs = srcDirSet.srcDirs.findAll {dir -> dir.exists()}
def optionsFile = project.file("${getTemporaryDir()}/javadoc-options.txt")
// create the directory, so relative link calculation knows that it's a directory:
@@ -316,14 +319,14 @@ class RenderJavadocTask extends DefaultTask {
outputDir.mkdirs();
def opts = []
- opts << [ '-overview', project.file("${srcDirs[0]}/overview.html") ]
- opts << [ '-sourcepath', srcDirs.join(File.pathSeparator) ]
- opts << [ '-subpackages', 'org.apache.solr' ]
- opts << [ '-d', outputDir ]
+ opts << ['-overview', project.file("${srcDirs[0]}/overview.html")]
+ opts << ['-sourcepath', srcDirs.join(File.pathSeparator)]
+ opts << ['-subpackages', 'org.apache.solr']
+ 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'
}
@@ -333,29 +336,37 @@ 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 << [ '-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 << [
+ '-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 << [ '-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())
@@ -373,8 +384,10 @@ class RenderJavadocTask extends DefaultTask {
if (project.path != ':solr:test-framework') { //
findRenderTasksInDependencies()
.findAll({it.project.path != ':solr:solrj' && it.project.path != ':solr:solrj-zookeeper'}) // split packages
- .sort(false, Comparator.comparing { (it.project.name != 'core') as Boolean }.thenComparing(Comparator.comparing { it.path }))
- .each { otherTask ->
+ .sort(false,
+ Comparator.comparing {(it.project.name != 'core') as Boolean}
+ .thenComparing(Comparator.comparing {it.path}))
+ .each {otherTask ->
def otherProject = otherTask.project
// For relative links we compute the actual relative link between projects.
def crossLuceneSolr = (otherProject.docroot != project.docroot)
@@ -387,42 +400,44 @@ class RenderJavadocTask extends DefaultTask {
// For absolute links, we determine the target URL by assembling the full URL.
def value = solrDocUrl.getOrElse(null)
if (value) {
- allOfflineLinks.put("${value}/${otherProject.relativeDocPath}/".toString(), otherTask.outputDir)
+ allOfflineLinks.put("${value}/${otherProject.relativeDocPath}/".toString(),
+ otherTask.outputDir)
}
}
}
}
// Add offline links.
- allOfflineLinks.each { url, dir ->
- // Some sanity check/ validation here to ensure dir/package-list or dir/element-list is present.
+ allOfflineLinks.each {url, dir ->
+ // Some sanity check/validation here to ensure dir/package-list or dir/element-list is
+ // present.
if (!project.file("$dir/package-list").exists() &&
!project.file("$dir/element-list").exists()) {
throw new GradleException("Expected pre-rendered package-list or element-list at ${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") }
+ def jOpts = opts.findAll {opt -> opt instanceof String && opt.startsWith("-J")}
opts.removeAll(jOpts)
// Temporary file that holds all javadoc options for the current task (except jOpts)
- optionsFile.withWriter("UTF-8", { writer ->
+ optionsFile.withWriter("UTF-8", {writer ->
// escapes an option with single quotes or whitespace to be passed in the options.txt file for
- def escapeJavadocOption = { String s -> (s =~ /[ '"]/) ? ("'" + s.replaceAll(/[\\'"]/, /\\$0/) + "'") : s }
+ def escapeJavadocOption = {String s -> (s =~ /[ '"]/) ? ("'" + s.replaceAll(/[\\'"]/, /\\$0/) + "'") : s}
- opts.each { entry ->
+ opts.each {entry ->
if (entry instanceof List) {
- writer.write(entry.collect { escapeJavadocOption(it as String) }.join(" "))
+ writer.write(entry.collect {escapeJavadocOption(it as String)}.join(" "))
} else {
writer.write(escapeJavadocOption(entry as String))
}
@@ -434,23 +449,37 @@ 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") {
+ ant.concat(
+ destfile: "${outputDir}/stylesheet.css",
+ append: "true",
+ fixlastline: "true",
+ encoding: "UTF-8") {
filelist(dir: taskResources, files: "table_padding.css")
filelist(dir: project.file("${taskResources}/prettify"), files: "prettify.css")
}
// append prettify to scripts
- ant.concat(destfile: "${outputDir}/script.js", append: "true", fixlastline: "true", encoding: "UTF-8") {
- filelist(dir: project.file("${taskResources}/prettify"), files: "prettify.min.js inject-javadocs.js")
+ ant.concat(
+ destfile: "${outputDir}/script.js",
+ append: "true",
+ fixlastline: "true",
+ encoding: "UTF-8") {
+ filelist(dir: project.file("${taskResources}/prettify"),
+ files: "prettify.min.js inject-javadocs.js")
}
- ant.fixcrlf(srcdir: outputDir, includes: "stylesheet.css script.js", eol: "lf", fixlast: "true", encoding: "UTF-8")
+ ant.fixcrlf(
+ srcdir: outputDir,
+ includes: "stylesheet.css script.js",
+ eol: "lf",
+ fixlast: "true",
+ encoding: "UTF-8")
}
}
diff --git a/gradle/generation/javacc.gradle b/gradle/generation/javacc.gradle
index 0b70ba656ee..9eaa7fe3c5d 100644
--- a/gradle/generation/javacc.gradle
+++ b/gradle/generation/javacc.gradle
@@ -1,5 +1,4 @@
import java.nio.charset.Charset
-import java.util.function.Function
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -33,14 +32,14 @@ configure(rootProject) {
description "Regenerate sources for corresponding javacc grammar files."
group "generation"
- dependsOn allprojects.collect { prj -> prj.tasks.withType(JavaCCTask) }
+ dependsOn allprojects.collect {prj -> prj.tasks.withType(JavaCCTask)}
}
}
-def commonCleanups = { FileTree generatedFiles ->
+def commonCleanups = {FileTree generatedFiles ->
// This is a minor typo in a comment that nonetheless people have hand-corrected in the past.
- generatedFiles.matching({ include "CharStream.java" }).each {file ->
- modifyFile(file, { text ->
+ generatedFiles.matching({include "CharStream.java"}).each {file ->
+ modifyFile(file, {text ->
return text.replace(
"implemetation",
"implementation");
@@ -48,7 +47,7 @@ def commonCleanups = { FileTree generatedFiles ->
}
generatedFiles.each {file ->
- modifyFile(file, { text ->
+ modifyFile(file, {text ->
// Normalize EOLs and tabs (EOLs are a side-effect of modifyFile).
text = text.replace("\t", " ");
text = text.replaceAll("JavaCC - OriginalChecksum=[^*]+", "(filtered)")
@@ -57,8 +56,8 @@ def commonCleanups = { FileTree generatedFiles ->
})
}
- generatedFiles.matching({ include "*TokenManager.java" }).each { file ->
- modifyFile(file, { text ->
+ generatedFiles.matching({include "*TokenManager.java"}).each {file ->
+ modifyFile(file, {text ->
// Remove redundant imports.
text = text.replaceAll(
/(?m)^import .+/,
@@ -66,14 +65,13 @@ def commonCleanups = { FileTree generatedFiles ->
// Add CharStream imports.
text = text.replaceAll(
/package (.+)/,
-'''package $1
+ '''package $1
import javax.annotation.processing.Generated;
import org.apache.lucene.queryparser.charstream.CharStream;'''.trim())
text = text.replace(
- "/** Token Manager. */",
-'''/** Token Manager. */
-@Generated("JavaCC")'''
- )
+ "/** Token Manager. */",
+ '''/** Token Manager. */
+@Generated("JavaCC")''')
// Eliminates redundant cast message.
text = text.replace(
"int hiByte = (int)(curChar >> 8);",
@@ -98,9 +96,9 @@ configure(project(":solr:core")) {
javaccFile = file('src/java/org/apache/solr/parser/QueryParser.jj')
afterGenerate << commonCleanups
- afterGenerate << { FileTree generatedFiles ->
- generatedFiles.matching { include "QueryParser.java" }.each { file ->
- modifyFile(file, { text ->
+ afterGenerate << {FileTree generatedFiles ->
+ generatedFiles.matching {include "QueryParser.java"}.each {file ->
+ modifyFile(file, {text ->
text = text.replace(
"public QueryParser(CharStream ",
"protected QueryParser(CharStream ")
@@ -160,7 +158,7 @@ class JavaCCTask extends DefaultTask {
// and can post-process them easily.
def tempDir = this.getTemporaryDir()
tempDir.mkdirs()
- project.delete project.fileTree(tempDir, { include: "**/*.java" })
+ project.delete project.fileTree(tempDir, {include: "**/*.java"})
def targetDir = javaccFile.parentFile
logger.lifecycle("Recompiling JavaCC: ${project.rootDir.relativePath(javaccFile)}")
diff --git a/gradle/generation/local-settings.gradle b/gradle/generation/local-settings.gradle
index e164b890706..936455008cf 100644
--- a/gradle/generation/local-settings.gradle
+++ b/gradle/generation/local-settings.gradle
@@ -15,7 +15,6 @@
* 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'.
@@ -34,8 +33,7 @@ configure(rootProject) {
"com.sun.tools.javac.parser",
"com.sun.tools.javac.tree",
"com.sun.tools.javac.util"
- ].stream()
- .allMatch(pkg -> jdkCompilerModule.isExported(pkg, gradleModule))
+ ].stream().allMatch {pkg -> jdkCompilerModule.isExported(pkg, gradleModule)}
if (!internalsExported) {
throw new GradleException(
diff --git a/gradle/generation/regenerate.gradle b/gradle/generation/regenerate.gradle
index 541f05fbbd3..4d5c09c6d7d 100644
--- a/gradle/generation/regenerate.gradle
+++ b/gradle/generation/regenerate.gradle
@@ -22,8 +22,8 @@ configure(rootProject) {
/**
* 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") }
+ 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)
diff --git a/gradle/globals.gradle b/gradle/globals.gradle
index 70aa7ef3ab5..32a480eb48a 100644
--- a/gradle/globals.gradle
+++ b/gradle/globals.gradle
@@ -36,13 +36,13 @@ allprojects {
// Artifacts will have names after full gradle project path
// so :solr:core will have solr-core.jar, etc.
project.archivesBaseName = project.path
- .replaceAll("^:", "")
- .replace(':', '-')
- .replace("-modules-", "-")
+ .replaceAll("^:", "")
+ .replace(':', '-')
+ .replace("-modules-", "-")
project.ext {
// Utility method to support passing overrides via -P or -D.
- propertyOrDefault = { propName, defValue ->
+ propertyOrDefault = {propName, defValue ->
def result
if (project.hasProperty(propName)) {
result = project.getProperty(propName)
@@ -57,25 +57,26 @@ allprojects {
}
// System environment variable or default.
- envOrDefault = { envName, defValue ->
+ envOrDefault = {envName, defValue ->
return Objects.requireNonNullElse(System.getenv(envName), defValue);
}
// Either a project, system property, environment variable or default value.
- propertyOrEnvOrDefault = { propName, envName, defValue ->
+ propertyOrEnvOrDefault = {propName, envName, defValue ->
return propertyOrDefault(propName, envOrDefault(envName, defValue));
}
// Locate script-relative resource folder. This is context-sensitive so pass
// the right buildscript (top-level).
- scriptResources = { buildscript ->
+ scriptResources = {buildscript ->
return file(buildscript.sourceFile.absolutePath.replaceAll('.gradle$', ""))
}
- failOrWarn = { propName, message, errors ->
+ failOrWarn = {propName, message, errors ->
if (errors) {
def shouldFail = Boolean.valueOf(propertyOrDefault(propName, true))
- def msg = message + (shouldFail ? " (skip with -P${propName}=false)" : "") + ":\n${errors.join("\n")}"
+ def msg = message + (shouldFail ? " (skip with -P${propName}=false)" : "") +
+ ":\n${errors.join("\n")}"
if (shouldFail) {
throw new GradleException(msg)
@@ -87,7 +88,7 @@ allprojects {
// Utility function similar to project.exec but not emitting
// any output unless an error code is returned from the executed command.
- quietExec = { closure ->
+ quietExec = {closure ->
// Resolve any properties against the provided closure.
resolveStrategy = Closure.DELEGATE_ONLY
delegate = closure.delegate
@@ -97,7 +98,7 @@ allprojects {
boolean saveIgnoreExitValue
ExecSpec saveExecSpec
- outputFile.withOutputStream { output ->
+ 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
@@ -109,7 +110,7 @@ allprojects {
}
}
- result = project.exec { ExecSpec execSpec ->
+ result = project.exec {ExecSpec execSpec ->
project.configure(execSpec, closure)
saveIgnoreExitValue = execSpec.ignoreExitValue
@@ -139,7 +140,7 @@ allprojects {
}
// Convert a list of strings, tasks and task providers into resolved tasks or task providers.
- resolveTaskRefs = { List<Object> refs ->
+ resolveTaskRefs = {List<Object> refs ->
def resolved = refs.collect {
if (it instanceof Task) return it
if (it instanceof TaskProvider) return it
@@ -153,7 +154,7 @@ allprojects {
// 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 ->
+ mustRunInOrder = {List<Object> taskList ->
project.afterEvaluate {
def resolved = resolveTaskRefs(taskList)
@@ -171,7 +172,7 @@ allprojects {
// 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().any { it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/ }
+ isCIBuild = System.getenv().keySet().any {it ==~ /(?i)((JENKINS|HUDSON)(_\w+)?|CI)/}
// Assign different java version for client-side modules 'api' and 'solrj*'
var isSolrJ = project.name.matches("^(solrj.*|api)\$")
diff --git a/gradle/hacks/dummy-outputs.gradle b/gradle/hacks/dummy-outputs.gradle
index f3d074d14b1..ccbdff4fe3a 100644
--- a/gradle/hacks/dummy-outputs.gradle
+++ b/gradle/hacks/dummy-outputs.gradle
@@ -18,7 +18,7 @@
// 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 ->
+def setupDummyOutputs = {Task task ->
File dummyOutput = file("${task.project.buildDir}/tasks/${task.name}/dummy-output.txt")
task.outputs.file(dummyOutput)
task.doLast {
@@ -31,11 +31,12 @@ def setupDummyOutputs = { Task task ->
allprojects {
tasks.matching {
it.name.startsWith("ecjLint") ||
- it.name in [
+ it.name in [
"gradlewScriptsTweaked",
"validateSourcePatterns",
"validateLogCalls"
- ] }.configureEach { Task task ->
+ ]
+ }.configureEach {Task task ->
task.logger.info("Setting up ${task.path} as no-output.")
setupDummyOutputs(task)
}
diff --git a/gradle/hacks/global-exclude-dependencies.gradle b/gradle/hacks/global-exclude-dependencies.gradle
index 09981d46109..6b0573de6c0 100644
--- a/gradle/hacks/global-exclude-dependencies.gradle
+++ b/gradle/hacks/global-exclude-dependencies.gradle
@@ -17,7 +17,7 @@
// Globally exclude known bad dependencies to ensure they aren't included in any transitive dependency.
-allprojects { prj ->
+allprojects {prj ->
// Ensure we only limit to compilation and runtime configurations for the JavaPlugin.
// There doesn't seem to be a way to pull this out of JavaPlugin programatically.
// https://docs.gradle.org/current/userguide/java_plugin.html#tab:configurations
@@ -38,17 +38,20 @@ allprojects { prj ->
JavaPlugin.TEST_COMPILE_CLASSPATH_CONFIGURATION_NAME,
JavaPlugin.TEST_RUNTIME_CLASSPATH_CONFIGURATION_NAME
]
- configurations.matching { it.name in configNames }.all {
+ configurations.matching {it.name in configNames}.all {
exclude group: 'log4j', module: 'log4j' // use SLF4j
exclude group: "ch.qos.logback" // use SLF4j
exclude group: 'commons-logging', module: 'commons-logging' // use SLF4j
exclude group: 'com.google.code.findbugs', module: 'jsr305' // Uses GPL license
- exclude group: 'com.google.code.findbugs', module: 'annotations' // Use Spotbugs Annotations as replacement
- exclude group: 'javax.annotation', module: 'javax.annotation-api' // Replaced with jakarta.annotation-api
+ // Use Spotbugs Annotations as replacement
+ exclude group: 'com.google.code.findbugs', module: 'annotations'
+ // Replaced with jakarta.annotation-api
+ exclude group: 'javax.annotation', module: 'javax.annotation-api'
exclude group: 'org.slf4j', module: 'slf4j-log4j12' // don't include log4j 1.x
exclude group: 'org.apache.yetus', module: 'audience-annotations' // Don't need annotations
- exclude group: 'org.codehaus.mojo', module: 'animal-sniffer-annotations' // Don't need annotations
- exclude group: 'net.jcip', module: 'jcip-annotations' // use com.github.stephenc.jcip instead
+ // Don't need annotations
+ exclude group: 'org.codehaus.mojo', module: 'animal-sniffer-annotations'
// be conservative on what's added here. Affects all Java project compilation and runtime.
+ exclude group: 'net.jcip', module: 'jcip-annotations' // use com.github.stephenc.jcip instead
}
}
diff --git a/gradle/hacks/gradle-archives.gradle b/gradle/hacks/gradle-archives.gradle
index a10a640a44c..98033226e6a 100644
--- a/gradle/hacks/gradle-archives.gradle
+++ b/gradle/hacks/gradle-archives.gradle
@@ -13,11 +13,11 @@
* 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 ->
+ tasks.withType(AbstractArchiveTask).configureEach {task ->
duplicatesStrategy = DuplicatesStrategy.FAIL
reproducibleFileOrder = true
dirMode = 0755
diff --git a/gradle/hacks/turbocharge-jvm-opts.gradle b/gradle/hacks/turbocharge-jvm-opts.gradle
index fb7ee6e5375..4440dda488d 100644
--- a/gradle/hacks/turbocharge-jvm-opts.gradle
+++ b/gradle/hacks/turbocharge-jvm-opts.gradle
@@ -17,48 +17,48 @@
// LUCENE-9861: tune JVM options for short-lived java subprocesses.
allprojects {
- def vmOpts = [
- '-XX:+UseParallelGC',
- '-XX:TieredStopAtLevel=1',
- '-XX:ActiveProcessorCount=1'
- ]
+ 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 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) {
- jvmArgs += vmOpts
- }
+ // 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) {
+ 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
- }
- }
- })
- }
+ // 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
index 2b7e56ad947..4a5a4dfb288 100644
--- a/gradle/hacks/wipe-temp.gradle
+++ b/gradle/hacks/wipe-temp.gradle
@@ -13,7 +13,7 @@
* 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.
- */
+ */
// See LUCENE-9471. We redirect temporary location for gradle
// so that it doesn't pollute user's tmp. Wipe it during a clean though.
@@ -33,7 +33,7 @@ allprojects {
task wipeTaskTemp() {
doLast {
- temps.each { temp ->
+ temps.each {temp ->
project.delete fileTree(temp).matching {
include "jar_extract*"
}
diff --git a/gradle/help.gradle b/gradle/help.gradle
index 3e3e5f957d8..25632fbe3d0 100644
--- a/gradle/help.gradle
+++ b/gradle/help.gradle
@@ -32,7 +32,7 @@ configure(rootProject) {
["Docker", "dev-docs/gradle-help/docker.txt", "Building Solr Docker images."],
]
- helpFiles.each { section, path, sectionInfo ->
+ helpFiles.each {section, path, sectionInfo ->
task "help${section}" {
group = 'Help (developer guides and hints)'
description = sectionInfo
@@ -48,7 +48,7 @@ configure(rootProject) {
println "This is the Solr gradle build. See some guidelines, "
println "ant-equivalent commands, etc. under dev-docs/gradle-help/*; or type:"
println ""
- helpFiles.each { section, path, sectionInfo ->
+ helpFiles.each {section, path, sectionInfo ->
println String.format(Locale.ROOT,
" gradlew :help%-16s # %s", section, sectionInfo)
}
@@ -59,7 +59,7 @@ configure(rootProject) {
task allHelpFilesExit() {
doFirst {
- helpFiles.each { section, path, sectionInfo ->
+ helpFiles.each {section, path, sectionInfo ->
if (!rootProject.file(path).exists()) {
throw new GradleException("Help file missing: ${path} (correct help.gradle)")
}
diff --git a/gradle/ide/eclipse.gradle b/gradle/ide/eclipse.gradle
index d7d453c39d9..f0084146575 100644
--- a/gradle/ide/eclipse.gradle
+++ b/gradle/ide/eclipse.gradle
@@ -25,7 +25,7 @@ configure(rootProject) {
apply plugin: "eclipse"
def eclipseJavaVersion = propertyOrDefault("eclipse.javaVersion", libs.versions.java.min.get())
- def relativize = { other -> rootProject.rootDir.relativePath(other).toString() }
+ def relativize = {other -> rootProject.rootDir.relativePath(other).toString()}
eclipse {
project {
@@ -38,20 +38,24 @@ configure(rootProject) {
defaultOutputDir = file('build/eclipse')
file {
- beforeMerged { classpath -> classpath.entries.removeAll { it.kind == "src" } }
+ beforeMerged {classpath -> classpath.entries.removeAll {it.kind == "src"}}
- whenMerged { classpath ->
- def projects = allprojects.findAll { prj ->
+ whenMerged {classpath ->
+ def projects = allprojects.findAll {prj ->
return prj.plugins.hasPlugin(JavaPlugin) &&
- prj.path != ":solr:solr-ref-guide"
+ prj.path != ":solr:solr-ref-guide"
}
Set<String> sources = []
Set<File> jars = []
- projects.each { prj ->
- prj.sourceSets.each { sourceSet ->
- sources += sourceSet.java.srcDirs.findAll { dir -> dir.exists() }.collect { dir -> relativize(dir) }
- sources += sourceSet.resources.srcDirs.findAll { dir -> dir.exists() }.collect { dir -> relativize(dir) }
+ projects.each {prj ->
+ prj.sourceSets.each {sourceSet ->
+ 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
@@ -62,10 +66,12 @@ configure(rootProject) {
jars += prj.configurations.testCompileClasspath.resolve()
}
- classpath.entries += sources.sort().collect {name -> new SourceFolder(name, "build/eclipse/" + name) }
- classpath.entries += jars.unique().findAll { location -> location.isFile() }.collect { location ->
- new LibEntry(location.toString())
- }
+ classpath.entries +=
+ sources.sort().collect {name -> new SourceFolder(name, "build/eclipse/" + name)}
+ classpath.entries +=
+ jars.unique().findAll {location -> location.isFile()}.collect {location ->
+ new LibEntry(location.toString())
+ }
}
}
}
diff --git a/gradle/java/jar-manifest.gradle b/gradle/java/jar-manifest.gradle
index 25cae7ea523..764981a2fbb 100644
--- a/gradle/java/jar-manifest.gradle
+++ b/gradle/java/jar-manifest.gradle
@@ -18,65 +18,65 @@
// Configures JAR manifest entries
subprojects {
- // Declare these inline for now. Don't know if it makes sense to declare them
- // per-project.
- def title = "Apache Solr Search Server: ${project.name}"
- def implementationTitle = "org.apache.solr"
- def legaleseDir = rootDir
+ // Declare these inline for now. Don't know if it makes sense to declare them
+ // per-project.
+ def title = "Apache Solr Search Server: ${project.name}"
+ def implementationTitle = "org.apache.solr"
+ def legaleseDir = rootDir
- // Apply the manifest to any JAR or WAR file created by any project,
- // excluding those explicitly listed.
- tasks.withType(Jar)
- .configureEach { task ->
- // Compute git status once on the root project prior to assembling manifest.
- dependsOn ":gitStatus"
+ // Apply the manifest to any JAR or WAR file created by any project,
+ // excluding those explicitly listed.
+ 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 : ""
+ // 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 {
- def sysProps = System.properties
- def manifestUsername = sysProps.getOrDefault('manifest.username', sysProps['user.name'])
- return "${project.version} ${gitRev} - ${manifestUsername} - ${buildDate} ${buildTime}"
- }
- }
+ // 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 {
+ def sysProps = System.properties
+ def manifestUsername = sysProps.getOrDefault('manifest.username', sysProps['user.name'])
+ return "${project.version} ${gitRev} - ${manifestUsername} - ${buildDate} ${buildTime}"
+ }
+ }
- manifest {
- attributes([
- "Extension-Name" : implementationTitle,
+ manifest {
+ attributes([
+ "Extension-Name": implementationTitle,
- "Implementation-Vendor" : "The Apache Software Foundation",
- "Implementation-Title" : implementationTitle,
- "Implementation-Version": implementationVersion,
+ "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,
+ "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}",
+ // 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']}"
- ])
- }
+ "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']}"
+ ])
+ }
- // Copy legalese into META-INF.
- metaInf {
- from(legaleseDir, {
- include "LICENSE.txt"
- include "NOTICE.txt"
- })
- }
- }
-}
\ No newline at end of file
+ // 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
index c6f7786d994..8a7af8b04d7 100644
--- a/gradle/java/javac.gradle
+++ b/gradle/java/javac.gradle
@@ -36,31 +36,31 @@ allprojects {
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
options.compilerArgs += [
- "-Xlint:-deprecation",
- "-Xlint:-serial",
- "-Xlint:cast",
- "-Xlint:classfile",
- "-Xlint:dep-ann",
- "-Xlint:divzero",
- "-Xlint:empty",
- "-Xlint:fallthrough",
- "-Xlint:finally",
- "-Xlint:options",
- "-Xlint:overrides",
- "-Xlint:processing",
- "-Xlint:rawtypes",
- "-Xlint:static",
- "-Xlint:try",
- "-Xlint:unchecked",
- "-Xlint:varargs",
- "-Xdoclint:all/protected",
- "-Xdoclint:-missing",
- "-Xdoclint:-accessibility",
- "-Xlint:synchronization",
- "-Xlint:text-blocks",
- "-proc:none", // proc:none was added because of LOG4J2-1925 / JDK-8186647
- "-Xlint:removal",
- "--should-stop=ifError=FLOW" // error-prone 2.41
+ "-Xlint:-deprecation",
+ "-Xlint:-serial",
+ "-Xlint:cast",
+ "-Xlint:classfile",
+ "-Xlint:dep-ann",
+ "-Xlint:divzero",
+ "-Xlint:empty",
+ "-Xlint:fallthrough",
+ "-Xlint:finally",
+ "-Xlint:options",
+ "-Xlint:overrides",
+ "-Xlint:processing",
+ "-Xlint:rawtypes",
+ "-Xlint:static",
+ "-Xlint:try",
+ "-Xlint:unchecked",
+ "-Xlint:varargs",
+ "-Xdoclint:all/protected",
+ "-Xdoclint:-missing",
+ "-Xdoclint:-accessibility",
+ "-Xlint:synchronization",
+ "-Xlint:text-blocks",
+ "-proc:none", // proc:none was added because of LOG4J2-1925 / JDK-8186647
+ "-Xlint:removal",
+ "--should-stop=ifError=FLOW" // error-prone 2.41
]
if (propertyOrDefault("javac.failOnWarnings", true).toBoolean()) {
@@ -73,7 +73,7 @@ allprojects {
configure(project(":solr:benchmark")) {
plugins.withType(JavaPlugin) {
tasks.named('compileJava').configure {
- options.compilerArgs -= [ "-Werror", "-proc:none" ]
+ options.compilerArgs -= ["-Werror", "-proc:none"]
options.compilerArgs += "-Xlint:none"
}
}
diff --git a/gradle/lucene-dev/lucene-dev-repo-composite.gradle b/gradle/lucene-dev/lucene-dev-repo-composite.gradle
index 62274b32e6c..3dc91409e6a 100644
--- a/gradle/lucene-dev/lucene-dev-repo-composite.gradle
+++ b/gradle/lucene-dev/lucene-dev-repo-composite.gradle
@@ -24,13 +24,12 @@ import java.util.function.BiFunction
// 3) An auto-wired 'lucene' subfolder, if present. To skip auto-wiring, pass
// a blank value in step 2: "-Plucene.dev.path=".
-
// This script is applied in settings.gradle and later at build time: these two contexts
// are distinctively different and have separate (and limited) APIs.
def configuringSettings = (rootProject instanceof org.gradle.api.initialization.ProjectDescriptor)
// Accessor for -P properties from settings or at build time.
-BiFunction<String, String, String> resolvePropertyValue = { propertyName, defValue ->
+BiFunction<String, String, String> resolvePropertyValue = {propertyName, defValue ->
if (configuringSettings) {
return settings.ext.properties.getOrDefault(propertyName, defValue)
} else {
@@ -38,10 +37,9 @@ BiFunction<String, String, String> resolvePropertyValue = { propertyName, defVal
}
}
-def PROP_FORCE_VERSION="lucene.dev.version"
-def PROP_FORCE_PATH="lucene.dev.path"
-def READ_ACCESS_PROPERTY="lucene-dev-path.dir"
-
+def PROP_FORCE_VERSION = "lucene.dev.version"
+def PROP_FORCE_PATH = "lucene.dev.path"
+def READ_ACCESS_PROPERTY = "lucene-dev-path.dir"
def forcedLuceneVersion = resolvePropertyValue(PROP_FORCE_VERSION, null)
if (forcedLuceneVersion != null) {
@@ -55,7 +53,8 @@ if (forcedLuceneVersion != null) {
tasks.withType(Test) {
def userHome = System.properties.get('user.home')
- systemProperty READ_ACCESS_PROPERTY, file("${userHome}/.m2/repository/org/apache/lucene").absolutePath
+ systemProperty READ_ACCESS_PROPERTY,
+ file("${userHome}/.m2/repository/org/apache/lucene").absolutePath
}
configurations.all {
@@ -96,7 +95,6 @@ if (propertyValue != null) {
luceneDevRepo = defaultLuceneDevRepo
}
-
if (luceneDevRepo != null) {
// Allow turning off this auto-wiring via -Dlucene.dev.repo=false (can't be a -P property because
// at settings evaluation time we don't have project properties yet).
@@ -105,7 +103,8 @@ if (luceneDevRepo != null) {
// We can't just substitute all references without looking at the versoin because
// plugin dependencies then also get substituted and everything crashes.
String luceneVersion = libs.versions.apache.lucene.get()
- logger.lifecycle("Local Lucene development repository will be used substituting ${luceneVersion}: ${luceneDevRepo}")
+ logger
+ .lifecycle("Local Lucene development repository will be used substituting ${luceneVersion}: ${luceneDevRepo}")
// Include Lucene repository as a composite and substitute module names.
includeBuild(luceneDevRepo) {
@@ -116,17 +115,19 @@ if (luceneDevRepo != null) {
// important to have the names match.
name = 'lucene-root'
dependencySubstitution {
- all { DependencySubstitution dependency ->
+ all {DependencySubstitution dependency ->
if (dependency.requested instanceof ModuleComponentSelector) {
def moduleSelector = (ModuleComponentSelector) dependency.requested
- if (moduleSelector.group == "org.apache.lucene" && moduleSelector.version == luceneVersion) {
+ if (moduleSelector.group == "org.apache.lucene" && moduleSelector.version ==
+ luceneVersion) {
// Map Maven artifact name to lucene module name.
def projectModuleName =
moduleSelector.moduleIdentifier.name
.replaceFirst("^lucene-analysis-", ":lucene:analysis:")
.replaceFirst("^lucene-", ":lucene:")
- logger.info("Substituting Lucene dependency ${moduleSelector} with an included build project: ${projectModuleName}")
+ logger
+ .info("Substituting Lucene dependency ${moduleSelector} with an included build project: ${projectModuleName}")
dependency.useTarget(project(projectModuleName))
}
}
@@ -136,19 +137,22 @@ if (luceneDevRepo != null) {
} else {
// We're being applied at build-time and Lucene development repository exists. Configure
// certain aspects of the build so that things work with it.
-
+
// replace luceneBaseVersionProvider by one evaluating the included build:
configure(rootProject) {
- def line = new File(gradle.includedBuild('lucene-root').projectDir, 'build.gradle').readLines("UTF-8").find { it =~ /\bbaseVersion\s*=\s*['"]/ }
+ def line = new File(gradle.includedBuild('lucene-root').projectDir, 'build.gradle').readLines(
+ "UTF-8").find {it =~ /\bbaseVersion\s*=\s*['"]/}
if (!line) {
throw new GradleException('Cannot extract Lucene baseVersion from build.gradle file.')
}
def luceneBaseVersion = evaluate(line)
-
- logger.lifecycle("Local Lucene development repository will override luceneBaseVersion with: {}", luceneBaseVersion)
+
+ logger.lifecycle(
+ "Local Lucene development repository will override luceneBaseVersion with: {}",
+ luceneBaseVersion)
ext {
- luceneBaseVersionProvider = provider { luceneBaseVersion }
+ luceneBaseVersionProvider = provider {luceneBaseVersion}
}
}
diff --git a/gradle/maven/defaults-maven.gradle b/gradle/maven/defaults-maven.gradle
index 2b2da08d198..ea20f908ad1 100644
--- a/gradle/maven/defaults-maven.gradle
+++ b/gradle/maven/defaults-maven.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// Maven publications and configuration.
//
// the 'published' list contains an explicit list of all projects
@@ -38,7 +37,7 @@ configure(rootProject) {
}
}
-configure(subprojects.findAll { it.path in rootProject.published }) { prj ->
+configure(subprojects.findAll {it.path in rootProject.published}) {prj ->
apply plugin: 'maven-publish'
apply plugin: 'signing'
@@ -198,7 +197,7 @@ configure(subprojects.findAll { it.path in rootProject.published }) { prj ->
if (project(":solr:distribution").ext.useGpgForSigning) {
useGpgCmd()
}
- required { project(":solr:distribution").ext.withSignedArtifacts }
+ required {project(":solr:distribution").ext.withSignedArtifacts}
sign publishing.publications.jars
}
}
diff --git a/gradle/maven/maven-local.gradle b/gradle/maven/maven-local.gradle
index 9d415b89463..794040e760e 100644
--- a/gradle/maven/maven-local.gradle
+++ b/gradle/maven/maven-local.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// This adds a root project task to install all artifacts to a build-local
// Maven repository (so that pom files can be manually reviewed).
@@ -42,7 +41,7 @@ configure(rootProject) {
delete mavenLocalDir
}
- configure(subprojects.findAll { it.path in rootProject.published }) {
+ configure(subprojects.findAll {it.path in rootProject.published}) {
plugins.withType(PublishingPlugin) {
publishing {
repositories {
@@ -53,11 +52,11 @@ configure(rootProject) {
}
}
- tasks.matching { it.name == "publishJarsPublicationToMavenLocal" }.all { task ->
+ tasks.matching {it.name == "publishJarsPublicationToMavenLocal"}.all {task ->
mavenToLocalRepo.dependsOn task
}
- tasks.matching { it.name == "publishJarsPublicationToBuildRepository" }.all { task ->
+ tasks.matching {it.name == "publishJarsPublicationToBuildRepository"}.all {task ->
// Clean local repo prior to republishing artifacts.
task.dependsOn mavenLocalClean
// Attach to root project's mavenLocal task.
@@ -65,4 +64,4 @@ configure(rootProject) {
}
}
}
-}
\ No newline at end of file
+}
diff --git a/gradle/node.gradle b/gradle/node.gradle
index fe128ea1f4a..067b56f4471 100644
--- a/gradle/node.gradle
+++ b/gradle/node.gradle
@@ -16,46 +16,46 @@
*/
configure([project(":solr:packaging"), project(":solr:solr-ref-guide"), project(":solr:webapp")]) {
- apply plugin: libs.plugins.nodegradle.node.get().pluginId
-
- def npmRegistry = "${ -> propertyOrEnvOrDefault("solr.npm.registry", "SOLR_NPM_REGISTRY", '') }"
- if (!npmRegistry.isEmpty()) {
- tasks.npmSetup {
- args.addAll(['--registry', npmRegistry])
- }
-
- afterEvaluate {
- tasks.withType(NpmTask).each { npmTask ->
- npmTask.environment.put('NPM_CONFIG_REGISTRY', npmRegistry)
- }
- tasks.withType(NpxTask).each { npxTask ->
- npxTask.environment.put('NPM_CONFIG_REGISTRY', npmRegistry)
- }
- }
+ apply plugin: libs.plugins.nodegradle.node.get().pluginId
+
+ def npmRegistry = "${-> propertyOrEnvOrDefault("solr.npm.registry", "SOLR_NPM_REGISTRY", '')}"
+ if (!npmRegistry.isEmpty()) {
+ tasks.npmSetup {
+ args.addAll(['--registry', npmRegistry])
}
- project.ext {
- nodeProjectDir = layout.projectDirectory.dir(".gradle/node")
+ afterEvaluate {
+ tasks.withType(NpmTask).each {npmTask ->
+ npmTask.environment.put('NPM_CONFIG_REGISTRY', npmRegistry)
+ }
+ tasks.withType(NpxTask).each {npxTask ->
+ npxTask.environment.put('NPM_CONFIG_REGISTRY', npmRegistry)
+ }
}
+ }
+
+ project.ext {
+ nodeProjectDir = layout.projectDirectory.dir(".gradle/node")
+ }
- node {
- download = true
- version = libs.versions.nodejs.get()
+ node {
+ download = true
+ version = libs.versions.nodejs.get()
- def nodeDistUrl = "${ -> propertyOrEnvOrDefault("solr.node.distUrl", "SOLR_NODE_DIST_URL", '') }"
- if (!nodeDistUrl.isEmpty()) {
- distBaseUrl = nodeDistUrl
- }
+ def nodeDistUrl = "${-> propertyOrEnvOrDefault("solr.node.distUrl", "SOLR_NODE_DIST_URL", '')}"
+ if (!nodeDistUrl.isEmpty()) {
+ distBaseUrl = nodeDistUrl
+ }
- // The directory where Node.js is unpacked (when download is true)
- workDir = file("${project.ext.nodeProjectDir.getAsFile().path}/nodejs")
+ // The directory where Node.js is unpacked (when download is true)
+ workDir = file("${project.ext.nodeProjectDir.getAsFile().path}/nodejs")
- // The directory where npm is installed (when a specific version is defined)
- npmWorkDir = file("${project.ext.nodeProjectDir.getAsFile().path}/npm")
+ // The directory where npm is installed (when a specific version is defined)
+ npmWorkDir = file("${project.ext.nodeProjectDir.getAsFile().path}/npm")
- // The Node.js project directory location
- // This is where the package.json file and node_modules directory are located
- // By default it is at the root of the current project
- nodeProjectDir = project.ext.nodeProjectDir
- }
+ // The Node.js project directory location
+ // This is where the package.json file and node_modules directory are located
+ // By default it is at the root of the current project
+ nodeProjectDir = project.ext.nodeProjectDir
+ }
}
diff --git a/gradle/solr/packaging.gradle b/gradle/solr/packaging.gradle
index d8988555dad..d1706b4c577 100644
--- a/gradle/solr/packaging.gradle
+++ b/gradle/solr/packaging.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// For Solr, a 'resolve' task is much more complex. There are three folders:
// lib/
// test-lib/
@@ -36,7 +35,8 @@
// I don't know how to untie these two cleanly.
//
-configure(allprojects.findAll {project -> project.path.startsWith(":solr:modules:") || project.path == ":solr:cross-dc-manager" }) {
+configure(allprojects
+ .findAll {project -> project.path.startsWith(":solr:modules:") || project.path == ":solr:cross-dc-manager"}) {
plugins.withType(JavaPlugin) {
project.ext {
packagingDir = file("${buildDir}/packaging")
@@ -74,12 +74,12 @@ configure(allprojects.findAll {project -> project.path.startsWith(":solr:modules
task assemblePackaging(type: Sync) {
from "README.md"
- from (tasks.jar, {
+ from(tasks.jar, {
into "lib"
})
- from ({
- def externalLibs = configurations.runtimeLibs.copyRecursive { dep ->
+ from({
+ def externalLibs = configurations.runtimeLibs.copyRecursive {dep ->
if (dep instanceof org.gradle.api.artifacts.ProjectDependency) {
return !dep.dependencyProject.path.startsWith(":solr")
} else {
@@ -109,7 +109,7 @@ configure(allprojects.findAll {project -> project.path.startsWith(":solr:modules
// 2) runtime dependencies
// What remains is this module's "own" test dependency.
from({
- def testRuntimeLibs = configurations.testRuntimeClasspath.copyRecursive { dep ->
+ def testRuntimeLibs = configurations.testRuntimeClasspath.copyRecursive {dep ->
!(dep instanceof org.gradle.api.artifacts.ProjectDependency)
}
diff --git a/gradle/solr/solr-forbidden-apis.gradle b/gradle/solr/solr-forbidden-apis.gradle
index f7bdb5dd4da..0e030d0824a 100644
--- a/gradle/solr/solr-forbidden-apis.gradle
+++ b/gradle/solr/solr-forbidden-apis.gradle
@@ -15,11 +15,10 @@
* limitations under the License.
*/
-
// Why does solr exclude these from forbidden API checks?
configure(project(":solr:core")) {
- tasks.matching { it.name == "forbiddenApisMain" || it.name == "forbiddenApisTest" }.all {
+ tasks.matching {it.name == "forbiddenApisMain" || it.name == "forbiddenApisTest"}.all {
exclude "org/apache/solr/internal/**"
}
}
diff --git a/gradle/testing/alternative-jdk-support.gradle b/gradle/testing/alternative-jdk-support.gradle
index 6977059771f..ab1a9d49b8d 100644
--- a/gradle/testing/alternative-jdk-support.gradle
+++ b/gradle/testing/alternative-jdk-support.gradle
@@ -1,4 +1,3 @@
-
import org.gradle.internal.jvm.JavaInfo
import org.gradle.internal.jvm.Jvm
import org.gradle.internal.jvm.inspection.JvmInstallationMetadata
@@ -49,8 +48,9 @@ if (jvmGradle != jvmCurrent) {
task altJvmWarning() {
doFirst {
- def jvmInfo = { JavaInfo javaInfo ->
- JvmInstallationMetadata jvmMetadata = jvmDetector.getMetadata(InstallationLocation.userDefined(javaInfo.javaHome, "specific path"))
+ 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})"
}
@@ -78,7 +78,7 @@ if (jvmGradle != jvmCurrent) {
// Javadoc compilation.
def javadocExecutable = jvmCurrent.javadocExecutable
- tasks.matching { it.name == "renderJavadoc" || it.name == "renderSiteJavadoc" }.configureEach {
+ tasks.matching {it.name == "renderJavadoc" || it.name == "renderSiteJavadoc"}.configureEach {
dependsOn ":altJvmWarning"
executable = javadocExecutable.toString()
}
@@ -87,6 +87,9 @@ if (jvmGradle != jvmCurrent) {
// Set up root project's properties.
rootProject.ext.runtimeJavaHome = jvmCurrent.javaHome
-rootProject.ext.runtimeJavaVersion = jvmDetector.getMetadata(InstallationLocation.userDefined(jvmCurrent.javaHome, "specific path")).getLanguageVersion()
+rootProject.ext.runtimeJavaVersion =
+ jvmDetector
+ .getMetadata(InstallationLocation.userDefined(jvmCurrent.javaHome, "specific path"))
+ .getLanguageVersion()
rootProject.ext.usesAltJvm = (jvmGradle != jvmCurrent);
diff --git a/gradle/testing/beasting.gradle b/gradle/testing/beasting.gradle
index 67c20140ba8..1e8abc0ff08 100644
--- a/gradle/testing/beasting.gradle
+++ b/gradle/testing/beasting.gradle
@@ -23,7 +23,8 @@
// 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')}
allprojects {
plugins.withType(JavaPlugin) {
@@ -37,7 +38,8 @@ allprojects {
if (beastingMode) {
if (rootProject.rootSeedUserProvided) {
- logger.warn("Root randomization seed is externally provided, all duplicated runs will use the same starting seed.")
+ logger.warn(
+ "Root randomization seed is externally provided, all duplicated runs will use the same starting seed.")
}
allprojects {
@@ -55,7 +57,7 @@ if (beastingMode) {
// 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 ->
+ def subtasks = (1..dups).collect {value ->
return tasks.create(name: "test_${value}", type: Test, {
failFast = true
doFirst {
@@ -81,7 +83,7 @@ if (beastingMode) {
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 ->
+ taskDependencies.getDependencies(this).each {subtask ->
subtask.filter.setCommandLineIncludePatterns(patterns)
}
}
@@ -89,4 +91,4 @@ class BeastTask extends DefaultTask {
@TaskAction
void run() {
}
-}
\ No newline at end of file
+}
diff --git a/gradle/testing/defaults-tests.gradle b/gradle/testing/defaults-tests.gradle
index 9eed9572fe2..06e22fdbc6b 100644
--- a/gradle/testing/defaults-tests.gradle
+++ b/gradle/testing/defaults-tests.gradle
@@ -33,31 +33,33 @@ allprojects {
// 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
+ 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",
- includeInReproLine: false],
+ value: {->
+ ((int) Math.max(1, Math.min(Runtime.runtime.availableProcessors() / 2.0, 4.0)))},
+ description: "Number of forked test JVMs",
+ includeInReproLine: false],
[propName: 'tests.haltonfailure', value: true, description: "Halt processing on test failure."],
// Default code cache size is 240m, but disabling C2 compiler shrinks it to 48m, which turns out to not be enough
[propName: 'tests.jvmargs',
- value: { -> propertyOrEnvOrDefault("tests.jvmargs", "TEST_JVM_ARGS", "-XX:TieredStopAtLevel=1 -XX:+UseParallelGC -XX:ActiveProcessorCount=1 -XX:ReservedCodeCacheSize=120m") },
- description: "Arguments passed to each forked JVM."],
+ value: {->
+ propertyOrEnvOrDefault("tests.jvmargs", "TEST_JVM_ARGS", "-XX:TieredStopAtLevel=1 -XX:+UseParallelGC -XX:ActiveProcessorCount=1 -XX:ReservedCodeCacheSize=120m")},
+ 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."],
+ 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 }
+ resolvedTestOption = {propName ->
+ def option = testOptions.find {entry -> entry.propName == propName}
if (option == null) {
throw new GradleException("No such test option: " + propName)
}
@@ -78,10 +80,11 @@ allprojects {
if (verboseMode && !verboseModeHookInstalled) {
verboseModeHookInstalled = true
if (gradle.startParameter.maxWorkerCount > 1) {
- gradle.taskGraph.whenReady { graph ->
- def testTasks = graph.allTasks.findAll { task -> task instanceof Test }
+ 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.")
+ throw new GradleException(
+ "Run your tests in verbose mode only with --max-workers=1 option passed to gradle.")
}
}
}
@@ -94,7 +97,7 @@ allprojects {
// 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 }
+ outputs.upToDateWhen {false}
}
maxParallelForks = resolvedTestOption("tests.jvms") as Integer
@@ -155,7 +158,8 @@ allprojects {
}
// Disable HTML report generation. The reports are big and slow to generate.
- reports.html.required = Boolean.parseBoolean(providers.gradleProperty("tests.html").getOrElse("false"))
+ reports.html.required =
+ Boolean.parseBoolean(providers.gradleProperty("tests.html").getOrElse("false"))
// Set up logging.
testLogging {
@@ -174,7 +178,10 @@ allprojects {
}
def spillDir = getTemporaryDir().toPath()
- def listener = buildinfra.newErrorReportingTestListener(test.testLogging, spillDir, testOutputsDir.toPath(), verboseMode)
+ def listener = buildinfra.newErrorReportingTestListener(test.testLogging,
+ spillDir,
+ testOutputsDir.toPath(),
+ verboseMode)
addTestOutputListener(listener)
addTestListener(listener)
diff --git a/gradle/testing/fail-on-no-tests.gradle b/gradle/testing/fail-on-no-tests.gradle
index db763d80277..06ad43ecfaa 100644
--- a/gradle/testing/fail-on-no-tests.gradle
+++ b/gradle/testing/fail-on-no-tests.gradle
@@ -27,25 +27,25 @@ configure(allprojects) {
}
}
-gradle.taskGraph.whenReady { graph ->
+gradle.taskGraph.whenReady {graph ->
def args = gradle.startParameter.taskNames
- def filters = args.findAll({ arg ->
+ 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 }
+ 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 ->
+ testTasks.each {task ->
task.doFirst {
executedTasks++
}
- task.afterSuite { desc, result ->
+ task.afterSuite {desc, result ->
executedTests += result.testCount
}
}
diff --git a/gradle/testing/failed-tests-at-end.gradle b/gradle/testing/failed-tests-at-end.gradle
index bd5f17b30a6..81539de87dc 100644
--- a/gradle/testing/failed-tests-at-end.gradle
+++ b/gradle/testing/failed-tests-at-end.gradle
@@ -25,24 +25,26 @@ def genFailInfo(def task, TestDescriptor desc) {
def historyUrl = "https://develocity.apache.org/scans/tests?search.rootProjectNames=solr-root&tests.container=$desc.className"
if (!isSuite) { // is test method specific
historyUrl += "&tests.test=$desc.name"
- historyUrl += " http://fucit.org/solr-jenkins-reports/history-trend-of-recent-failures.html#series/$name"
+ historyUrl +=
+ " http://fucit.org/solr-jenkins-reports/history-trend-of-recent-failures.html#series/$name"
}
def logName = buildinfra.getOutputLogName(desc.parent ?: desc)
def output = file("${task.testOutputsDir}/${logName}")
def repro = "./gradlew ${task.project.path}:test --tests \"${name}\" ${task.project.testOptionsForReproduceLine}"
- return ["name": name, "project": "${task.project.path}", "historyUrl": historyUrl, "output": output, "reproduce": repro]
+ return ["name": name, "project": "${task.project.path}", "historyUrl": historyUrl, "output":
+ output, "reproduce": repro]
}
allprojects {
plugins.withType(JavaPlugin).configureEach {
- tasks.withType(Test).configureEach { Test task ->
- afterTest { desc, result ->
+ tasks.withType(Test).configureEach {Test task ->
+ afterTest {desc, result ->
if (result.resultType == TestResult.ResultType.FAILURE) {
failedTests << genFailInfo(task, desc)
}
}
- afterSuite { desc, result ->
+ afterSuite {desc, result ->
if (result.exceptions) {
failedTests << genFailInfo(task, desc)
}
@@ -51,11 +53,12 @@ allprojects {
}
}
-gradle.buildFinished { result ->
+gradle.buildFinished {result ->
if (!failedTests) return
def formatted = failedTests
- .sort { a, b -> b.project <=> a.project }
- .collect { e -> """
+ .sort {a, b -> b.project <=> a.project}
+ .collect {e ->
+ """
- ${e.name} (${e.project})
Test history: ${e.historyUrl}
Test output: ${e.output}
diff --git a/gradle/testing/per-project-summary.gradle b/gradle/testing/per-project-summary.gradle
index 14acfab8a85..6d055c6a149 100644
--- a/gradle/testing/per-project-summary.gradle
+++ b/gradle/testing/per-project-summary.gradle
@@ -15,19 +15,18 @@
* limitations under the License.
*/
-
// Per-project test summary.
allprojects {
- tasks.withType(Test) { task ->
- afterSuite { desc, result ->
+ tasks.withType(Test) {task ->
+ afterSuite {desc, result ->
if (!desc.parent) {
if (result.testCount > 0) {
def components = [
- "test(s)" : result.testCount,
+ "test(s)": result.testCount,
"failure(s)": result.failedTestCount,
- "skipped" : result.skippedTestCount
- ].findAll { k, v -> v > 0 }.collect { k, v -> "$v $k" }.join(", ")
+ "skipped": result.skippedTestCount
+ ].findAll {k, v -> v > 0}.collect {k, v -> "$v $k"}.join(", ")
logger.lifecycle("${task.path} (${result.resultType}): ${components}")
}
diff --git a/gradle/testing/profiling.gradle b/gradle/testing/profiling.gradle
index 8b1e5147efc..51af4bca0cd 100644
--- a/gradle/testing/profiling.gradle
+++ b/gradle/testing/profiling.gradle
@@ -28,7 +28,8 @@ allprojects {
if (resolvedTestOption("tests.profile").toBoolean()) {
allprojects {
tasks.withType(Test) {
- jvmArgs("-XX:StartFlightRecording=dumponexit=true,maxsize=250M,settings=" + rootProject.file("gradle/testing/profiling.jfc"),
+ jvmArgs("-XX:StartFlightRecording=dumponexit=true,maxsize=250M,settings=" +
+ rootProject.file("gradle/testing/profiling.jfc"),
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+DebugNonSafepoints")
// delete any previous profile results
@@ -46,10 +47,12 @@ allprojects {
gradle.buildFinished {
if (!recordings.isEmpty()) {
- buildinfra.profileResultsClass().printReport(recordings.getFiles().collect { it.toString() },
+ buildinfra.profileResultsClass().printReport(recordings.getFiles().collect {it.toString()},
propertyOrDefault(ProfileResults.MODE_KEY, ProfileResults.MODE_DEFAULT) as String,
- Integer.parseInt(propertyOrDefault(ProfileResults.STACKSIZE_KEY, ProfileResults.STACKSIZE_DEFAULT)),
+ Integer.parseInt(propertyOrDefault(ProfileResults.STACKSIZE_KEY,
+ ProfileResults.STACKSIZE_DEFAULT)),
Integer.parseInt(propertyOrDefault(ProfileResults.COUNT_KEY, ProfileResults.COUNT_DEFAULT)),
- Boolean.parseBoolean(propertyOrDefault(ProfileResults.LINENUMBERS_KEY, ProfileResults.LINENUMBERS_DEFAULT)))
+ Boolean.parseBoolean(propertyOrDefault(ProfileResults.LINENUMBERS_KEY,
+ ProfileResults.LINENUMBERS_DEFAULT)))
}
}
diff --git a/gradle/testing/randomization.gradle b/gradle/testing/randomization.gradle
index e8cb4e8b061..83d71e7e907 100644
--- a/gradle/testing/randomization.gradle
+++ b/gradle/testing/randomization.gradle
@@ -71,7 +71,7 @@ configure(rootProject) {
// Any test task will trigger display of randomization settings.
allprojects {
- tasks.withType(Test) { task ->
+ tasks.withType(Test) {task ->
task.dependsOn rootProject.randomizationInfo
}
}
@@ -82,7 +82,8 @@ allprojects {
project.ext {
testOptions += [
// seed, repetition and amplification.
- [propName: 'tests.seed', value: { -> rootSeed }, description: "Sets the master randomization seed."],
+ [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: 1, description: "Value multiplier for randomized tests."],
[propName: 'tests.maxfailures', value: null, description: "Skip tests after a given number of failures."],
@@ -93,8 +94,9 @@ allprojects {
[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],
+ 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."],
@@ -110,10 +112,11 @@ allprojects {
[propName: 'tests.awaitsfix', value: null, description: "Enables or disables @AwaitsFix tests."],
[propName: 'tests.badapples', value: null, description: "Enables or disables @BadApple 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],
+ 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
[propName: 'tests.linedocsfile', value: 'europarl.lines.txt.gz', description: "Test data file path."],
// miscellaneous; some of them very weird.
@@ -124,7 +127,7 @@ allprojects {
}
// Add Solr-specific test configs settings.
-configure(allprojects.findAll {project -> project.path.startsWith(":solr") }) {
+configure(allprojects.findAll {project -> project.path.startsWith(":solr")}) {
plugins.withType(JavaPlugin) {
project.ext {
testOptions += [
@@ -139,14 +142,14 @@ configure(allprojects.findAll {project -> project.path.startsWith(":solr") }) {
allprojects {
plugins.withType(JavaPlugin) {
afterEvaluate {
- project.ext.testOptionsResolved = testOptions.findAll { opt ->
+ project.ext.testOptionsResolved = testOptions.findAll {opt ->
propertyOrDefault(opt.propName, opt.value) != null
- }.collectEntries { opt ->
+ }.collectEntries {opt ->
[(opt.propName): Objects.toString(resolvedTestOption(opt.propName))]
}
// Compute the "reproduce with" string.
- project.ext.testOptionsForReproduceLine = testOptions.findAll { opt ->
+ project.ext.testOptionsForReproduceLine = testOptions.findAll {opt ->
if (opt["includeInReproLine"] == false) {
return false
}
@@ -154,20 +157,21 @@ allprojects {
def defValue = Objects.toString(opt.value, null)
def value = testOptionsResolved[opt.propName]
return defValue != value
- }.collect { opt ->
+ }.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",
- "solr.test.leavetmpdir",
- ].find { prop ->
+ "tests.leaveTemporary",
+ "tests.leavetemporary",
+ "tests.leavetmpdir",
+ "solr.test.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}').")
+ logger
+ .lifecycle("Update your code to use the official 'tests.leaveTemporary' option (you used '${prop}').")
}
return v
}) {
@@ -175,7 +179,7 @@ allprojects {
}
// Append resolved test properties to the test task.
- tasks.withType(Test) { task ->
+ tasks.withType(Test) {
// TODO: we could remove some options that are only relevant to the build environment
// and not the test JVM itself.
systemProperties testOptionsResolved
@@ -190,25 +194,29 @@ allprojects {
failFast true
}
- // The Lucene version is only available after resolving was done, so add lately using a provider:
+ // The Lucene version is only available after resolving was done, so add lately using a
+ // provider:
jvmArgumentProviders.add({
def luceneMatchVersion = rootProject.luceneBaseVersionProvider.get()
return [
- "-Dtests.LUCENE_VERSION=${luceneMatchVersion}",
- "-Dtests.luceneMatchVersion=${luceneMatchVersion}",
+ "-Dtests.LUCENE_VERSION=${luceneMatchVersion}",
+ "-Dtests.luceneMatchVersion=${luceneMatchVersion}",
]
} as CommandLineArgumentProvider)
- // 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 useSecurityManager = Boolean.parseBoolean(testOptionsResolved["tests.useSecurityManager"]);
+ // 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 useSecurityManager = Boolean
+ .parseBoolean(testOptionsResolved["tests.useSecurityManager"]);
// Allow the project to override this
if (project.ext.has("useSecurityManager")) {
useSecurityManager &= project.ext.get("useSecurityManager")
}
if (useSecurityManager) {
def commonSolrDir = project(':solr').layout.projectDirectory
- def javaSecurityPolicy = layout.projectDirectory.file("${resources}/policies/solr-tests.policy")
+ def javaSecurityPolicy = layout
+ .projectDirectory.file("${resources}/policies/solr-tests.policy")
jvmArgumentProviders.add(
new SecurityArgumentProvider(
commonSolrDir: commonSolrDir,
@@ -218,13 +226,21 @@ allprojects {
systemProperty 'java.security.manager', "default"
def gradleUserHome = project.gradle.getGradleUserHomeDir()
- systemProperty 'gradle.lib.dir', Path.of(project.class.location.toURI()).parent.toAbsolutePath().toString().replace('\\', '/')
- systemProperty 'gradle.worker.jar', Path.of("${gradleUserHome}/caches/${gradle.gradleVersion}/workerMain/gradle-worker.jar").toAbsolutePath().toString()
+ systemProperty 'gradle.lib.dir',
+ Path.of(project.class.location.toURI()).parent.toAbsolutePath().toString().replace(
+ '\\',
+ '/')
+ systemProperty 'gradle.worker.jar',
+ Path
+ .of("${gradleUserHome}/caches/${gradle.gradleVersion}/workerMain/gradle-worker.jar")
+ .toAbsolutePath()
+ .toString()
systemProperty 'gradle.user.home', gradleUserHome.toPath().toAbsolutePath().toString()
}
doFirst {
- logger.debug("Will use test opts:\n" + testOptionsResolved.collect {k,v -> "${k}: ${v}"}.sort().join("\n"))
+ logger.debug("Will use test opts:\n" +
+ testOptionsResolved.collect {k, v -> "${k}: ${v}"}.sort().join("\n"))
}
}
}
@@ -242,7 +258,7 @@ allprojects {
doFirst {
println "Test options for project ${project.path} and seed \"${rootSeed}\":"
- testOptions.sort { a, b -> a.propName.compareTo(b.propName) }.each { opt ->
+ testOptions.sort {a, b -> a.propName.compareTo(b.propName)}.each {opt ->
def defValue
def computedValue = false
if (opt.value instanceof Closure) {
@@ -258,7 +274,8 @@ allprojects {
(defValue != value ? "! " : computedValue ? "C " : " "),
opt.propName,
value,
- (computedValue ? "(!= default: computed) " : (defValue != value ? "(!= default: ${defValue}) " : "")) + opt.description)
+ (computedValue ? "(!= default: computed) " :
+ (defValue != value ? "(!= default: ${defValue}) " : "")) + opt.description)
}
}
}
diff --git a/gradle/testing/retry-test.gradle b/gradle/testing/retry-test.gradle
index 4759b3fe2cf..90466d8d2b0 100644
--- a/gradle/testing/retry-test.gradle
+++ b/gradle/testing/retry-test.gradle
@@ -16,16 +16,16 @@
*/
allprojects {
- plugins.withType(JavaPlugin) {
- tasks.withType(Test) {
- develocity.testRetry {
- if (isCIBuild) {
- // For more info on params: https://github.com/gradle/test-retry-gradle-plugin
- maxRetries = 3
- maxFailures = 10
- failOnPassedAfterRetry = true
- }
- }
+ plugins.withType(JavaPlugin) {
+ tasks.withType(Test) {
+ develocity.testRetry {
+ if (isCIBuild) {
+ // For more info on params: https://github.com/gradle/test-retry-gradle-plugin
+ maxRetries = 3
+ maxFailures = 10
+ failOnPassedAfterRetry = true
}
+ }
}
-}
\ No newline at end of file
+ }
+}
diff --git a/gradle/testing/slowest-tests-at-end.gradle b/gradle/testing/slowest-tests-at-end.gradle
index d24e523394d..fc76eb52a26 100644
--- a/gradle/testing/slowest-tests-at-end.gradle
+++ b/gradle/testing/slowest-tests-at-end.gradle
@@ -29,26 +29,27 @@ allprojects {
]
}
- tasks.withType(Test) { task ->
+ tasks.withType(Test) {task ->
if (resolvedTestOption("tests.slowestTests").toBoolean()) {
- afterTest { desc, result ->
+ afterTest {desc, result ->
def duration = (result.getEndTime() - result.getStartTime())
allTests << [
- name : "${desc.className.replaceAll('.+\\.', "")}.${desc.name} (${project.path})",
+ name: "${desc.className.replaceAll('.+\\.', "")}.${desc.name} (${project.path})",
duration: duration
]
}
}
if (resolvedTestOption("tests.slowestSuites").toBoolean()) {
- afterSuite { desc, result ->
- // Gradle reports runner times as well, omit anything that isn't attached to a concrete class.
+ 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 << [
- name : "${desc.className.replaceAll('.+\\.', "")} (${project.path})",
+ name: "${desc.className.replaceAll('.+\\.', "")} (${project.path})",
duration: duration
]
}
@@ -58,14 +59,14 @@ allprojects {
}
}
-gradle.buildFinished { result ->
+gradle.buildFinished {result ->
if (result.getFailure() == null) {
if (allTests) {
def slowest = allTests
- .sort { a, b -> b.duration.compareTo(a.duration) }
+ .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) }
+ .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 " +
@@ -75,10 +76,10 @@ gradle.buildFinished { result ->
if (allSuites) {
def slowest = allSuites
- .sort { a, b -> b.duration.compareTo(a.duration) }
+ .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) }
+ .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 " +
diff --git a/gradle/validation/check-broken-links.gradle b/gradle/validation/check-broken-links.gradle
index a2e3e01f112..3bec07db6a0 100644
--- a/gradle/validation/check-broken-links.gradle
+++ b/gradle/validation/check-broken-links.gradle
@@ -37,35 +37,36 @@ class CheckBrokenLinksTask extends DefaultTask {
@InputDirectory
@PathSensitive(PathSensitivity.RELATIVE)
final DirectoryProperty docsDir = project.objects.directoryProperty()
- .fileProvider(project.providers.provider { project.docroot })
+ .fileProvider(project.providers.provider {project.docroot})
@InputFile
@PathSensitive(PathSensitivity.RELATIVE)
File script = project.rootProject.file("dev-tools/scripts/checkJavadocLinks.py")
@OutputFile
- Provider<RegularFile> outputFile = project.layout.buildDirectory.file('check-broken-links-output.txt')
+ Provider<RegularFile> outputFile = project.layout.buildDirectory.file(
+ 'check-broken-links-output.txt')
@TaskAction
def check() {
def result
- outputFile.get().asFile.withOutputStream { output ->
+ outputFile.get().asFile.withOutputStream {output ->
result = project.exec {
executable project.externalTool("python3")
ignoreExitValue = true
standardOutput = output
errorOutput = output
args = [
- "-B",
- script.absolutePath,
- docsDir.get().getAsFile()
+ "-B",
+ script.absolutePath,
+ docsDir.get().getAsFile()
]
}
}
if (result.getExitValue() != 0) {
println "Broken links check failed. First lines of the output:"
- outputFile.get().asFile.readLines().take(20).each { line ->
+ outputFile.get().asFile.readLines().take(20).each {line ->
println line
}
throw new GradleException("Broken links check failed. Command output at: ${outputFile.get()}")
diff --git a/gradle/validation/check-environment.gradle b/gradle/validation/check-environment.gradle
index f56e9fa4e78..6ad28f60968 100644
--- a/gradle/validation/check-environment.gradle
+++ b/gradle/validation/check-environment.gradle
@@ -34,7 +34,7 @@ configure(rootProject) {
def minJavaVersion = JavaVersion.toVersion(libs.versions.java.min.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')}]")
+ + "[${System.getProperty('java.vm.name')} ${System.getProperty('java.vm.version')}]")
}
// If we're regenerating the wrapper, skip the check.
diff --git a/gradle/validation/dependencies.gradle b/gradle/validation/dependencies.gradle
index a6a8ca60ce9..87c00ae2ed7 100644
--- a/gradle/validation/dependencies.gradle
+++ b/gradle/validation/dependencies.gradle
@@ -17,89 +17,90 @@
// Helper function for specifying stable versions for dependency updates
// https://github.com/ben-manes/gradle-versions-plugin
-def isNonStable = { String version ->
- def stableKeyword = ['RELEASE', 'FINAL', 'GA'].any { it -> version.toUpperCase().contains(it) }
- def regex = /^[0-9,.v-]+(-r)?$/
- return !stableKeyword && !(version ==~ regex)
+def isNonStable = {String version ->
+ def stableKeyword = ['RELEASE', 'FINAL', 'GA'].any {it -> version.toUpperCase().contains(it)}
+ def regex = /^[0-9,.v-]+(-r)?$/
+ return !stableKeyword && !(version ==~ regex)
}
buildscript {
- configurations.classpath {
- resolutionStrategy.activateDependencyLocking()
- }
+ configurations.classpath {
+ resolutionStrategy.activateDependencyLocking()
+ }
}
// Configure sanity check for conflicting dependencies across certain configurations
allprojects {
- // Enable dependency locking in all modules and configurations
- dependencyLocking {
- lockAllConfigurations()
- // Ignore platform-specific dependencies (e.g. from Kotlin multiplatform module)
- // that may cause different lock state depending on the OS
- ignoredDependencies.add("org.jetbrains.compose.desktop:desktop-jvm-*")
- ignoredDependencies.add("org.jetbrains.skiko:skiko-awt-runtime-*")
- }
+ // Enable dependency locking in all modules and configurations
+ dependencyLocking {
+ lockAllConfigurations()
+ // Ignore platform-specific dependencies (e.g. from Kotlin multiplatform module)
+ // that may cause different lock state depending on the OS
+ ignoredDependencies.add("org.jetbrains.compose.desktop:desktop-jvm-*")
+ ignoredDependencies.add("org.jetbrains.skiko:skiko-awt-runtime-*")
+ }
- dependencies {
- modules {
- module("org.hamcrest:hamcrest-core") {
- replacedBy("org.hamcrest:hamcrest", "hamcrest-core was renamed to hamcrest")
- }
- }
+ dependencies {
+ modules {
+ module("org.hamcrest:hamcrest-core") {
+ replacedBy("org.hamcrest:hamcrest", "hamcrest-core was renamed to hamcrest")
+ }
}
+ }
}
// Configure version catalog cleanups plugin.
configure(rootProject) {
- apply plugin: libs.plugins.littlerobots.versioncatalogupdate.get().pluginId
+ apply plugin: libs.plugins.littlerobots.versioncatalogupdate.get().pluginId
- versionCatalogUpdate {
- sortByKey = true
- }
+ versionCatalogUpdate {
+ sortByKey = true
+ }
- tasks.matching { it.name == "tidy" }.configureEach {
- it.dependsOn(":versionCatalogFormat")
- }
+ tasks.matching {it.name == "tidy"}.configureEach {
+ it.dependsOn(":versionCatalogFormat")
+ }
- tasks.matching {
- it.path in [":versionCatalogUpdate"]
- }.configureEach {
- it.interactive = true
- }
+ tasks.matching {
+ it.path in [":versionCatalogUpdate"]
+ }.configureEach {
+ it.interactive = true
+ }
- tasks.register("updateLibs", {
- dependsOn ":versionCatalogUpdate"
- })
+ tasks.register("updateLibs", {
+ dependsOn ":versionCatalogUpdate"
+ })
- // on dependencyUpdates get only stable versions recommended if current version is stable
- // https://github.com/ben-manes/gradle-versions-plugin
- tasks.named("dependencyUpdates").configure {
- checkConstraints = true
- checkBuildEnvironmentConstraints = true
- rejectVersionIf {
- isNonStable(it.candidate.version) && !isNonStable(it.currentVersion)
- }
+ // on dependencyUpdates get only stable versions recommended if current version is stable
+ // https://github.com/ben-manes/gradle-versions-plugin
+ tasks.named("dependencyUpdates").configure {
+ checkConstraints = true
+ checkBuildEnvironmentConstraints = true
+ rejectVersionIf {
+ isNonStable(it.candidate.version) && !isNonStable(it.currentVersion)
}
+ }
}
allprojects {
- // Register task that allows lock-file generation in all modules
- tasks.register("resolveAndLockAll") {
- doFirst {
- // If the task is not directly used, do not enforce --write-locks to be provided
- assert !gradle.startParameter.taskNames.contains("resolveAndLockAll")
- || gradle.startParameter.writeDependencyLocks: "$path must be run from the command line with the `--write-locks` flag"
- }
- doLast {
- if (gradle.startParameter.writeDependencyLocks) {
- // Resolve and update locks only if --write-locks explicitly included
- // This may not be the case where this task is added as a dependency, like for "dependencies" task
- project.configurations.findAll {
- // Add any custom filtering on the configurations to be resolved
- it.canBeResolved
- }.each { it.resolve() }
- }
- }
+ // Register task that allows lock-file generation in all modules
+ tasks.register("resolveAndLockAll") {
+ doFirst {
+ // If the task is not directly used, do not enforce --write-locks to be provided
+ assert !gradle.startParameter.taskNames.contains("resolveAndLockAll")
+ || gradle.startParameter.writeDependencyLocks:
+ "$path must be run from the command line with the `--write-locks` flag"
+ }
+ doLast {
+ if (gradle.startParameter.writeDependencyLocks) {
+ // Resolve and update locks only if --write-locks explicitly included
+ // This may not be the case where this task is added as a dependency, like for "dependencies" task
+ project.configurations.findAll {
+ // Add any custom filtering on the configurations to be resolved
+ it.canBeResolved
+ }.each {it.resolve()}
+ }
}
+ }
}
diff --git a/gradle/validation/dependency-analyze.gradle b/gradle/validation/dependency-analyze.gradle
index 92125aba11c..ce0dfe066c2 100644
--- a/gradle/validation/dependency-analyze.gradle
+++ b/gradle/validation/dependency-analyze.gradle
@@ -18,7 +18,7 @@
// This adds gradle-dependency-analyze validation of project dependencies
// https://github.com/gradle-dependency-analyze/gradle-dependency-analyze
-allprojects { prj ->
+allprojects {prj ->
plugins.withId("java", {
prj.apply plugin: libs.plugins.cutterslade.analyze.get().pluginId
diff --git a/gradle/validation/ecj-lint.gradle b/gradle/validation/ecj-lint.gradle
index e8dd4e95a0a..c23fcdd195f 100644
--- a/gradle/validation/ecj-lint.gradle
+++ b/gradle/validation/ecj-lint.gradle
@@ -34,10 +34,10 @@ allprojects {
// 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 ->
- def srcDirs = sourceSet.java.srcDirs.findAll { dir -> dir.exists() }
+ def lintTasks = sourceSets.collect {sourceSet ->
+ def srcDirs = sourceSet.java.srcDirs.findAll {dir -> dir.exists()}
- tasks.create(sourceSet.getTaskName("ecjLint", null), JavaExec, {task ->
+ tasks.create(sourceSet.getTaskName("ecjLint", null), JavaExec, {
// 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
@@ -62,18 +62,18 @@ allprojects {
def tmpDst = getTemporaryDir()
workingDir tmpDst
- args += [ "-d", "none" ]
+ args += ["-d", "none"]
assert project.java.sourceCompatibility == project.java.targetCompatibility
// Compilation environment.
- 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 ]
+ 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]
doFirst {
tmpDst.mkdirs()
@@ -81,7 +81,7 @@ allprojects {
// Add classpath locations at execution time (can't resolve the
// configuration at evaluation time). Filter out non-existing entries
// (output folders for non-existing input source dirs like resources).
- def cpath = sourceSet.compileClasspath.filter { p -> p.exists() }
+ def cpath = sourceSet.compileClasspath.filter {p -> p.exists()}
if (!cpath.isEmpty()) {
args += ["-classpath", cpath.asPath]
}
diff --git a/gradle/validation/error-prone.gradle b/gradle/validation/error-prone.gradle
index 4863daa13e2..c36d03bf6c7 100644
--- a/gradle/validation/error-prone.gradle
+++ b/gradle/validation/error-prone.gradle
@@ -22,7 +22,8 @@ if (rootProject.usesAltJvm) {
}
if (!propertyOrDefault("validation.errorprone", isCIBuild).asBoolean()) {
- skipReason = "skipped on builds not running inside CI environments, pass -Pvalidation.errorprone=true to enable"
+ skipReason =
+ "skipped on builds not running inside CI environments, pass -Pvalidation.errorprone=true to enable"
}
if (skipReason) {
@@ -35,12 +36,12 @@ if (skipReason) {
}
}
-allprojects { prj ->
+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" }
+ 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 lockfiles are consistent with or without error prone.
@@ -61,7 +62,7 @@ allprojects { prj ->
errorprone libs.google.errorprone.core
}
- tasks.withType(JavaCompile) { task ->
+ tasks.withType(JavaCompile) {task ->
task.dependsOn ":checkJdkInternalsExportedToGradle"
options.errorprone.disableWarningsInGeneratedCode = true
@@ -262,7 +263,6 @@ allprojects { prj ->
'-Xep:ZoneIdOfZ:ERROR',
// END -- On by Default : ERROR
-
// BEGIN -- On by Default : WARNING
// '-Xep:ASTHelpersSuggestions:OFF', // we don't use ASTHelpers
// '-Xep:AddressSelection:OFF', // not relevant for Solr
diff --git a/gradle/validation/forbidden-apis.gradle b/gradle/validation/forbidden-apis.gradle
index 90f385755c8..8f5be2f0ead 100644
--- a/gradle/validation/forbidden-apis.gradle
+++ b/gradle/validation/forbidden-apis.gradle
@@ -21,26 +21,28 @@
def resources = scriptResources(buildscript)
// Only apply forbidden-apis to java projects.
-allprojects { prj ->
+allprojects {prj ->
plugins.withId("java", {
prj.apply plugin: libs.plugins.thetaphi.forbiddenapis.get().pluginId
// This helper method appends signature files based on a set of true
// dependencies from a given configuration.
- def dynamicSignatures = { configuration, suffix ->
+ def dynamicSignatures = {configuration, suffix ->
def resolvedMods = configuration.resolvedConfiguration.resolvedArtifacts
- .collect { a -> a.moduleVersion.id }
+ .collect {a -> a.moduleVersion.id}
def deps = resolvedMods
- .collect { id -> [
- "${id.group}.${id.name}.all.txt",
- "${id.group}.${id.name}.${suffix}.txt",
- ]}
+ .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 ->
+ deps.each {sig ->
def signaturesFile = file("${resources}/${sig}")
if (signaturesFile.exists()) {
logger.info("Signature file applied: ${sig}")
@@ -49,11 +51,11 @@ allprojects { prj ->
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 }
+ .findAll {id -> id.group == 'commons-io' && id.name == 'commons-io'}
+ .collect {id -> "${id.name}-unsafe-${id.version}" as String}
}
// Configure defaults for all sourceSets (main and test)
@@ -87,7 +89,7 @@ allprojects { prj ->
}
// Configure defaults for sourceSets.tools (if present).
- tasks.matching { it.name == "forbiddenApisTools" }.all {
+ tasks.matching {it.name == "forbiddenApisTools"}.all {
bundledSignatures += [
'jdk-unsafe',
'jdk-deprecated',
@@ -137,7 +139,7 @@ allprojects { prj ->
//
// 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.
- configure([forbiddenApisMain, forbiddenApisTest]) { task ->
+ configure([forbiddenApisMain, forbiddenApisTest]) {task ->
task.inputs.dir(file(resources))
}
})
diff --git a/gradle/validation/git-status.gradle b/gradle/validation/git-status.gradle
index 8a43e7c7b3d..36c1b4e5f60 100644
--- a/gradle/validation/git-status.gradle
+++ b/gradle/validation/git-status.gradle
@@ -42,9 +42,9 @@ configure(rootProject) {
doFirst {
try {
def repository = new FileRepositoryBuilder()
- .setWorkTree(rootProject.projectDir)
- .setMustExist(true)
- .build()
+ .setWorkTree(rootProject.projectDir)
+ .setMustExist(true)
+ .build()
def ref = repository.findRef("HEAD").getObjectId()
project.ext.gitRev = ref.name()
@@ -55,7 +55,8 @@ configure(rootProject) {
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)
+ throw new GradleException("jgit does not support git repository version at this location: ${dir}",
+ e)
}
}
}
@@ -68,14 +69,16 @@ configure(rootProject) {
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}")
+ 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}")
+ logger
+ .warn("WARNING: Directory is not a valid git checkout (won't check dirty files): ${rootProject.projectDir}")
}
} else {
// git ignores any folders which are empty (this includes folders with recursively empty sub-folders).
- def untrackedNonEmptyFolders = status.untrackedFolders.findAll { path ->
+ def untrackedNonEmptyFolders = status.untrackedFolders.findAll {path ->
File location = file("${rootProject.projectDir}/${path}")
boolean hasFiles = false
Files.walkFileTree(location.toPath(), new SimpleFileVisitor<Path>() {
@@ -99,15 +102,15 @@ configure(rootProject) {
"(modified)": status.modified,
"(untracked)": status.untracked,
"(untracked non-empty dir)": untrackedNonEmptyFolders
- ].collectMany { fileStatus, files ->
- files.collect {file -> " - ${file} ${fileStatus}" }
+ ].collectMany {fileStatus, files ->
+ files.collect {file -> " - ${file} ${fileStatus}"}
}.sort()
- if (offenders ) {
+ if (offenders) {
def propName = "validation.git.failOnModified"
def shouldFail = Boolean.valueOf(propertyOrDefault(propName, isCIBuild))
def msg = "Working copy is not a clean git checkout" +
- (shouldFail ? " (skip with -P${propName}=false)" : "") + ":\n${offenders.join("\n")}"
+ (shouldFail ? " (skip with -P${propName}=false)" : "") + ":\n${offenders.join("\n")}"
if (shouldFail) {
throw new GradleException(msg)
diff --git a/gradle/validation/gradlew-scripts-tweaked.gradle b/gradle/validation/gradlew-scripts-tweaked.gradle
index 2720e70617e..4835f42f0b1 100644
--- a/gradle/validation/gradlew-scripts-tweaked.gradle
+++ b/gradle/validation/gradlew-scripts-tweaked.gradle
@@ -21,7 +21,7 @@ import java.nio.charset.StandardCharsets
// don't fork a daemon subprocess on the initial run.
configure(rootProject) {
- task gradlewScriptsTweaked() { task ->
+ task gradlewScriptsTweaked() {task ->
def scripts = [
file("gradlew"),
file("gradlew.bat")
@@ -30,7 +30,7 @@ configure(rootProject) {
inputs.files(scripts)
doFirst {
- scripts.each { file ->
+ 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 (see SOLR-16641).")
diff --git a/gradle/validation/jar-checks.gradle b/gradle/validation/jar-checks.gradle
index 650a3b3337b..b0c97bb5158 100644
--- a/gradle/validation/jar-checks.gradle
+++ b/gradle/validation/jar-checks.gradle
@@ -50,17 +50,17 @@ configure(project(":solr")) {
// 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"],
+ "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],
- "SUN" : [name: "Sun Open Source License", noticeOptional: true],
+ "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],
+ "SUN": [name: "Sun Open Source License", noticeOptional: true],
"COMPOUND": [name: "Compound license (details in NOTICE file)."],
]
@@ -105,7 +105,8 @@ subprojects {
// globally (this seems like a bug to me). So we process each inherited configuration independently
// but make sure there are no other dependencies on jarValidation itself.
if (!configurations.jarValidation.dependencies.isEmpty()) {
- throw new GradleException("jarValidation must only inherit from other configurations (can't have its own dependencies).")
+ throw new GradleException(
+ "jarValidation must only inherit from other configurations (can't have its own dependencies).")
}
def excludeRules = configurations.jarValidation.excludeRules
@@ -121,7 +122,7 @@ subprojects {
}
ArrayDeque<ResolvedDependency> queue = new ArrayDeque<>()
- configurations.jarValidation.extendsFrom.each { conf ->
+ configurations.jarValidation.extendsFrom.each {conf ->
if (excludeRules && excludeRules.size() > 0) {
conf = conf.copyRecursive()
conf.canBeResolved = true
@@ -147,20 +148,20 @@ subprojects {
}
// Make sure we don't keep visiting the same children over and over again
- dep.children.each { child ->
+ dep.children.each {child ->
if (!seenDeps.contains(child)) {
queue.add(child)
}
}
- dep.moduleArtifacts.each { resolvedArtifact ->
+ 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() },
+ 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: []
@@ -182,19 +183,23 @@ subprojects {
doLast {
def errors = []
- jarInfos.each { dep ->
+ jarInfos.each {dep ->
def expectedChecksumFile = file("${licensesDir}/${dep.jarName}.sha1")
def forceLuceneVersion = project.properties['lucene.dev.version']
- if (dep.module.id.group == 'org.apache.lucene' && forceLuceneVersion != null && forceLuceneVersion.endsWith('-SNAPSHOT')) {
- logger.log(LogLevel.INFO, "Skipping jar checksum validation for local SNAPSHOT dependency ('${dep.module}')")
+ if (dep.module.id.group == 'org.apache.lucene' && forceLuceneVersion != null &&
+ forceLuceneVersion.endsWith('-SNAPSHOT')) {
+ logger.log(LogLevel.INFO,
+ "Skipping jar checksum validation for local SNAPSHOT dependency ('${dep.module}')")
} else if (!expectedChecksumFile.exists()) {
- errors << "Dependency checksum missing ('${dep.module}'), expected it at: ${expectedChecksumFile}"
+ errors <<
+ "Dependency checksum missing ('${dep.module}'), expected it at: ${expectedChecksumFile}"
} else {
dep.referencedFiles += expectedChecksumFile
def expected = expectedChecksumFile.getText("UTF-8").trim()
def actual = dep.checksum.get()
if (expected.compareToIgnoreCase(actual) != 0) {
- errors << "Dependency checksum mismatch ('${dep.module}'), expected it to be: ${expected}, but was: ${actual}"
+ errors <<
+ "Dependency checksum mismatch ('${dep.module}'), expected it to be: ${expected}, but was: ${actual}"
} else {
logger.log(LogLevel.INFO, "Dependency checksum OK ('${dep.module}')")
}
@@ -202,7 +207,8 @@ subprojects {
}
if (errors) {
- def msg = "Dependency checksum validation failed:\n - " + errors.join("\n - ") + "\n\nThese missing checksums can be generated using:\n ./gradlew updateLicenses"
+ def msg = "Dependency checksum validation failed:\n - " + errors.join("\n - ") +
+ "\n\nThese missing checksums can be generated using:\n ./gradlew updateLicenses"
if (failOnError) {
throw new GradleException(msg)
} else {
@@ -224,7 +230,7 @@ subprojects {
doLast {
def errors = []
- jarInfos.each { dep ->
+ jarInfos.each {dep ->
def baseName = dep.name
def found = []
def candidates = []
@@ -239,7 +245,8 @@ subprojects {
}
if (found.size() == 0) {
- errors << "License file missing ('${dep.module}'), expected it at: ${candidates.join(" or ")}," +
+ errors <<
+ "License file missing ('${dep.module}'), expected it at: ${candidates.join(" or ")}," +
" where [type] can be any of ${licenseTypes.keySet()}."
} else if (found.size() > 1) {
errors << "Multiple license files matching for ('${dep.module}'): ${found.join(", ")}"
@@ -252,15 +259,18 @@ subprojects {
def licenseName = m[0][1]
def licenseType = licenseTypes[licenseName]
if (!licenseType) {
- errors << "Unknown license type suffix for ('${dep.module}'): ${licenseFile} (must be one of ${licenseTypes.keySet()})"
+ errors <<
+ "Unknown license type suffix for ('${dep.module}'): ${licenseFile} (must be one of ${licenseTypes.keySet()})"
} else {
- logger.log(LogLevel.INFO, "Dependency license file OK ('${dep.module}'): " + licenseName)
+ logger
+ .log(LogLevel.INFO, "Dependency license file OK ('${dep.module}'): " + licenseName)
// Look for sibling NOTICE file.
def noticeFile = file(licenseFile.path.replaceAll(/\-LICENSE-.+/, "-NOTICE.txt"))
if (noticeFile.exists()) {
dep.referencedFiles += noticeFile
- logger.log(LogLevel.INFO, "Dependency notice file OK ('${dep.module}'): " + noticeFile)
+ logger
+ .log(LogLevel.INFO, "Dependency notice file OK ('${dep.module}'): " + noticeFile)
} else if (!licenseType.noticeOptional) {
errors << "Notice file missing for ('${dep.module}'), expected it at: ${noticeFile}"
}
@@ -288,13 +298,14 @@ def plist = []
plist.add(project(":solr"))
configure(plist) {
- def validationTasks = subprojects.collectMany { it.tasks.matching { it.name == "licenses" } }
- def jarInfoTasks = subprojects.collectMany { it.tasks.matching { it.name == "collectJarInfos" } }
+ 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() {
group = 'Dependency validation'
- description = "Write or update checksums of dependencies. May need to run gradlew --write-locks first if changing dependency versions"
+ description =
+ "Write or update checksums of dependencies. May need to run gradlew --write-locks first if changing dependency versions"
dependsOn jarInfoTasks
doLast {
@@ -310,7 +321,7 @@ configure(plist) {
})
def updated = []
- jarInfoTasks.collectMany { task -> task.project.jarInfos }.each { dep ->
+ jarInfoTasks.collectMany {task -> task.project.jarInfos}.each {dep ->
def expectedChecksumFile = file("${licensesDir}/${dep.jarName}.sha1")
def actual = dep.checksum.get()
if (expectedChecksumFile.exists()) {
@@ -324,7 +335,7 @@ configure(plist) {
expectedChecksumFile.write(actual + "\n", "UTF-8")
}
- updated.sort().each { line -> logger.log(LogLevel.LIFECYCLE, line) }
+ updated.sort().each {line -> logger.log(LogLevel.LIFECYCLE, line)}
}
}
@@ -332,9 +343,9 @@ configure(plist) {
// We add an ordering constraint that any validation task (or its dependency subgraph)
// must run after updateLicenses
validationTasks
- .collectMany { task -> [task, task.dependsOn]}
+ .collectMany {task -> [task, task.dependsOn]}
.flatten()
- .each { task ->
+ .each {task ->
task.mustRunAfter updateLicenses
}
@@ -348,23 +359,24 @@ configure(plist) {
doFirst {
def allReferenced = validationTasks
- // Only collect for enabled tasks: https://issues.apache.org/jira/browse/LUCENE-9780
- .findAll { it.enabled }
- .collectMany { task ->
- task.project.jarInfos.collectMany { it.referencedFiles }
+ // Only collect for enabled tasks: https://issues.apache.org/jira/browse/LUCENE-9780
+ .findAll {it.enabled}
+ .collectMany {task ->
+ task.project.jarInfos.collectMany {it.referencedFiles}
}
- .collect { it.toString() }
+ .collect {it.toString()}
def patterns = ext.exclude
def allExisting = fileTree(licensesDir, {
exclude patterns
- }).files.collect { it.toString() }
+ }).files.collect {it.toString()}
def dangling = (allExisting - allReferenced).sort()
if (dangling) {
gradle.buildFinished {
- logger.warn("WARNING: there were unreferenced files under license folder:\n - ${dangling.join("\n - ")}")
+ logger
+ .warn("WARNING: there were unreferenced files under license folder:\n - ${dangling.join("\n - ")}")
}
}
}
diff --git a/gradle/validation/measure-task-times.gradle b/gradle/validation/measure-task-times.gradle
index c495d8d560d..2cec3b05950 100644
--- a/gradle/validation/measure-task-times.gradle
+++ b/gradle/validation/measure-task-times.gradle
@@ -21,9 +21,9 @@ import java.util.stream.Collectors
// all projects).
if (propertyOrDefault("task.times", null) != null) {
- gradle.taskGraph.whenReady { TaskExecutionGraph graph ->
+ gradle.taskGraph.whenReady {TaskExecutionGraph graph ->
def taskTimes = new ConcurrentHashMap<String, Long>()
- def measured = graph.allTasks.findAll { task -> true }
+ def measured = graph.allTasks.findAll {task -> true}
graph.addTaskExecutionListener(new TaskExecutionListener() {
@Override
@@ -39,7 +39,7 @@ if (propertyOrDefault("task.times", null) != null) {
def stop = System.currentTimeMillis()
if (measured.contains(task)) {
if (taskState.didWork) {
- taskTimes.compute(task.path, { k, v -> stop - v })
+ taskTimes.compute(task.path, {k, v -> stop - v})
} else {
taskTimes.remove(task.path)
}
@@ -52,18 +52,18 @@ if (propertyOrDefault("task.times", null) != null) {
// 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))
- }
+ .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))
+ }
}
}
}
diff --git a/gradle/validation/owasp-dependency-check.gradle b/gradle/validation/owasp-dependency-check.gradle
index f6352877dda..4d7359ed9e1 100644
--- a/gradle/validation/owasp-dependency-check.gradle
+++ b/gradle/validation/owasp-dependency-check.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// This adds OWASP vulnerability validation of project dependencies
// If -Pvalidation.owasp=true is set the validation will also run as part of the check task.
diff --git a/gradle/validation/precommit.gradle b/gradle/validation/precommit.gradle
index cc298b8771f..02d03010016 100644
--- a/gradle/validation/precommit.gradle
+++ b/gradle/validation/precommit.gradle
@@ -30,17 +30,19 @@ configure(rootProject) {
// Attach all these tasks from all projects that have them.
// This uses lazy collections as they may not yet be defined.
- dependsOn allprojects.collect { prj ->
- prj.tasks.matching { task -> task.name in [
- "forbiddenApis",
- "licenses",
- "javadoc",
- "rat",
- "ecjLint",
- "validateLogCalls",
- "validateSourcePatterns",
- "spotlessCheck"
- ]}
+ dependsOn allprojects.collect {prj ->
+ prj.tasks.matching {task ->
+ task.name in [
+ "forbiddenApis",
+ "licenses",
+ "javadoc",
+ "rat",
+ "ecjLint",
+ "validateLogCalls",
+ "validateSourcePatterns",
+ "spotlessCheck"
+ ]
+ }
}
}
diff --git a/gradle/validation/rat-sources.gradle b/gradle/validation/rat-sources.gradle
index 90e7d3da5e3..1def580e765 100644
--- a/gradle/validation/rat-sources.gradle
+++ b/gradle/validation/rat-sources.gradle
@@ -19,278 +19,281 @@ import groovy.xml.NamespaceBuilder
// Configure rat dependencies for use in the custom task.
configure(rootProject) {
- configurations {
- ratDeps
- }
+ configurations {
+ ratDeps
+ }
- dependencies {
- ratDeps libs.apache.rat.rat
- }
+ dependencies {
+ ratDeps libs.apache.rat.rat
+ }
}
// Configure the rat validation task and all scanned directories.
allprojects {
- task("rat", type: RatTask) {
- group = 'Verification'
- description = 'Runs Apache Rat checks.'
-
- 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 recurse into local Lucene dev repo.
- exclude "/lucene"
-
- // 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 "**/*.xml"
- include "**/*.md"
- include "**/*.py"
- include "**/*.sh"
- include "**/*.bat"
- // include build.gradle but exclude .gradle directories
- include "**/*.gradle"
- exclude ".gradle/**"
-
- // Exclude Eclipse
- exclude ".metadata"
- exclude ".settings"
-
- // 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"
- exclude "src/**/*.svg"
- exclude "src/**/*.csv"
-
- // TODO: SOLR-15601: Some of these should carry the license, perhaps?
- exclude "**/*.html"
- exclude "**/*.json"
-
- // 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 ".idea"
- exclude ".muse"
- exclude ".git"
-
- // Exclude github stuff (templates, workflows).
- exclude ".github"
-
- exclude "dev-tools/scripts/cloud.sh"
- exclude "dev-tools/scripts/README.md"
- exclude "dev-tools/scripts/create_line_file_docs.py"
-
- // Exclude new CHANGELOG and version-summary for each release
- exclude "CHANGELOG.md"
- exclude "changelog/**/version-summary.md"
- exclude "changelog/.templates/*.md"
- exclude "changelog/archive.md"
-
- // 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/**"
- break
-
- case ":solr:modules:clustering":
- exclude "src/test-files/META-INF/services/*"
- break
-
- case ":solr:modules:langid":
- exclude "**/langdetect-profiles/*"
- break
-
- case ":solr:modules:ltr":
- // TODO: SOLR-15601: Some of these should carry the license, perhaps?
- exclude "**/*.py"
- break
-
- case ":solr:modules:scripting":
- // TODO: SOLR-15601: Some of these should carry the license, perhaps?
- exclude "**/*.js"
- break
-
- case ":solr:modules:s3-repository":
- exclude "src/test-files/s3.conf" // empty file
- break
-
- case ":solr:documentation":
- exclude "src/markdown/*.md"
- break
-
- case ":solr:core":
- exclude "**/htmlStripReaderTest.html"
- exclude "src/resources/*.json"
- exclude "src/resources/*.xml"
- exclude "src/test-files/**/*.csv"
- exclude "src/test-files/**/*.json"
- exclude "src/test-files/**/*.aff"
- exclude "src/test-files/**/*.dic"
- exclude "src/test-files/**/*.conf"
- exclude "src/test-files/**/external_eff"
- exclude "src/test-files/**/*.incl"
- exclude "src/test-files/**/*-snippet-*.xml"
- break
-
- case ":solr:server":
- exclude "**/*.xml"
- exclude "**/*.sh"
- exclude "**/*.bat"
- break
-
- case ":solr:webapp":
- exclude "web/img/**"
- break
-
- case ":solr:solr-ref-guide":
- include "*.yml"
- include "**/*.adoc"
- exclude "ui-src/**"
- exclude "node_modules/**"
- break
-
- case ":solr:docker":
- exclude "tests/**/*.xml"
- break
-
- case ":solr:example":
- exclude "**/*.xml"
- exclude "films/README.md"
- break
-
- case ":solr:solrj":
- exclude "src/**/*.json"
- exclude "src/test-files/**/*.cfg"
- exclude "src/test-files/**/*.xml"
- break
- }
- })
- inputFileTrees.add(defaultScanFileTree)
- }
+ task("rat", type: RatTask) {
+ group = 'Verification'
+ description = 'Runs Apache Rat checks.'
+
+ 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 recurse into local Lucene dev repo.
+ exclude "/lucene"
+
+ // 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 "**/*.xml"
+ include "**/*.md"
+ include "**/*.py"
+ include "**/*.sh"
+ include "**/*.bat"
+ // include build.gradle but exclude .gradle directories
+ include "**/*.gradle"
+ exclude ".gradle/**"
+
+ // Exclude Eclipse
+ exclude ".metadata"
+ exclude ".settings"
+
+ // 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"
+ exclude "src/**/*.svg"
+ exclude "src/**/*.csv"
+
+ // TODO: SOLR-15601: Some of these should carry the license, perhaps?
+ exclude "**/*.html"
+ exclude "**/*.json"
+
+ // 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 ".idea"
+ exclude ".muse"
+ exclude ".git"
+
+ // Exclude github stuff (templates, workflows).
+ exclude ".github"
+
+ exclude "dev-tools/scripts/cloud.sh"
+ exclude "dev-tools/scripts/README.md"
+ exclude "dev-tools/scripts/create_line_file_docs.py"
+
+ // Exclude new CHANGELOG and version-summary for each release
+ exclude "CHANGELOG.md"
+ exclude "changelog/**/version-summary.md"
+ exclude "changelog/.templates/*.md"
+ exclude "changelog/archive.md"
+
+ // 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/**"
+ break
+
+ case ":solr:modules:clustering":
+ exclude "src/test-files/META-INF/services/*"
+ break
+
+ case ":solr:modules:langid":
+ exclude "**/langdetect-profiles/*"
+ break
+
+ case ":solr:modules:ltr":
+ // TODO: SOLR-15601: Some of these should carry the license, perhaps?
+ exclude "**/*.py"
+ break
+
+ case ":solr:modules:scripting":
+ // TODO: SOLR-15601: Some of these should carry the license, perhaps?
+ exclude "**/*.js"
+ break
+
+ case ":solr:modules:s3-repository":
+ exclude "src/test-files/s3.conf" // empty file
+ break
+
+ case ":solr:documentation":
+ exclude "src/markdown/*.md"
+ break
+
+ case ":solr:core":
+ exclude "**/htmlStripReaderTest.html"
+ exclude "src/resources/*.json"
+ exclude "src/resources/*.xml"
+ exclude "src/test-files/**/*.csv"
+ exclude "src/test-files/**/*.json"
+ exclude "src/test-files/**/*.aff"
+ exclude "src/test-files/**/*.dic"
+ exclude "src/test-files/**/*.conf"
+ exclude "src/test-files/**/external_eff"
+ exclude "src/test-files/**/*.incl"
+ exclude "src/test-files/**/*-snippet-*.xml"
+ break
+
+ case ":solr:server":
+ exclude "**/*.xml"
+ exclude "**/*.sh"
+ exclude "**/*.bat"
+ break
+
+ case ":solr:webapp":
+ exclude "web/img/**"
+ break
+
+ case ":solr:solr-ref-guide":
+ include "*.yml"
+ include "**/*.adoc"
+ exclude "ui-src/**"
+ exclude "node_modules/**"
+ break
+
+ case ":solr:docker":
+ exclude "tests/**/*.xml"
+ break
+
+ case ":solr:example":
+ exclude "**/*.xml"
+ exclude "films/README.md"
+ break
+
+ case ":solr:solrj":
+ exclude "src/**/*.json"
+ exclude "src/test-files/**/*.cfg"
+ exclude "src/test-files/**/*.xml"
+ break
+ }
+ })
+ inputFileTrees.add(defaultScanFileTree)
+ }
}
/**
* An Apache RAT adapter that validates whether files contain acceptable licenses.
*/
class RatTask extends DefaultTask {
- @InputFiles
- 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.rootProject.configurations.ratDeps.asPath
- 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")
- }
+ @InputFiles
+ 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.rootProject.configurations.ratDeps.asPath
+ 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}"
- }
- }
- def checkProp = "validation.rat.failOnError"
- project.failOrWarn(checkProp, "Detected license header issues", errors)
+ }
+
+ 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}"
+ }
}
-
- @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')}?")
- }
- }
+ def checkProp = "validation.rat.failOnError"
+ project.failOrWarn(checkProp, "Detected license header issues", errors)
+ }
+
+ @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/solr.config-file-sanity.gradle b/gradle/validation/solr.config-file-sanity.gradle
index 3b50843afeb..2a13d283813 100644
--- a/gradle/validation/solr.config-file-sanity.gradle
+++ b/gradle/validation/solr.config-file-sanity.gradle
@@ -27,12 +27,12 @@ configure(project(":solr")) {
[
file("server/solr/configsets"),
file("example")
- ].each { configsetsDir ->
+ ].each {configsetsDir ->
def configFiles = fileTree(configsetsDir, {
include "**/solrconfig.xml"
})
- configFiles.each { file ->
+ configFiles.each {file ->
def content = file.getText("UTF-8")
if (!content.contains("<luceneMatchVersion>${matchVersion}<")) {
throw new GradleException("Configset does not refer to the correct luceneMatchVersion (${matchVersion}): ${file.absolutePath}")
@@ -41,14 +41,14 @@ configure(project(":solr")) {
}
def configsetsDir = file("server/solr/configsets")
- def subdirs = configsetsDir.listFiles({file -> file.isDirectory() } as FileFilter)
+ def subdirs = configsetsDir.listFiles({file -> file.isDirectory()} as FileFilter)
if (subdirs.size() == 0) {
throw new GradleException("No sub-directories found under ${configsetsDir}?")
}
- subdirs.each { dir ->
- if (fileTree(dir, { include "**/solrconfig.xml" }).asList().isEmpty()) {
+ subdirs.each {dir ->
+ if (fileTree(dir, {include "**/solrconfig.xml"}).asList().isEmpty()) {
throw new GradleException("No solrconfig.xml file under: ${dir}")
}
}
diff --git a/gradle/validation/spotless.gradle b/gradle/validation/spotless.gradle
index 91c3f88deb7..719da568381 100644
--- a/gradle/validation/spotless.gradle
+++ b/gradle/validation/spotless.gradle
@@ -20,27 +20,30 @@
* spotless and Google Java Format.
*/
-configure(allprojects) { prj ->
+configure(allprojects) {prj ->
plugins.withType(JavaPlugin) {
prj.apply plugin: libs.plugins.diffplug.spotless.get().pluginId
project.ext {
- spotlessJavaSetup = (Action){
+ spotlessJavaSetup = (Action) {
it.toggleOffOn() // obviously, only to be used sparingly.
// 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.
//
// it.licenseHeaderFile(file("${resources}/asl-header.txt"), '^(\\s*package)')
- it.setLineEndings(Enum.valueOf(rootProject.buildscript.classLoader.loadClass("com.diffplug.spotless.LineEnding"), "UNIX"))
+ it
+ .setLineEndings(Enum.valueOf(rootProject.buildscript.classLoader.loadClass(
+ "com.diffplug.spotless.LineEnding"), "UNIX"))
it.endWithNewline()
it.googleJavaFormat(libs.versions.google.javaformat.get())
- it.custom('Refuse wildcard imports', { line ->
+ it.custom('Refuse wildcard imports', {line ->
// Wildcard imports can't be resolved by spotless itself.
// This will require the developer themselves to adhere to best practices.
if (line =~ /\nimport .*\*;/) {
- throw new AssertionError("Do not use wildcard imports. 'spotlessApply' cannot resolve this issue.")
+ throw new AssertionError(
+ "Do not use wildcard imports. 'spotlessApply' cannot resolve this issue.")
}
line
})
@@ -59,11 +62,11 @@ configure(allprojects) { prj ->
case ":solr:core":
// These are excluded since they are generated by javacc
targetExclude "src/java/org/apache/solr/parser/ParseException.java",
- "src/java/org/apache/solr/parser/QueryParser.java",
- "src/java/org/apache/solr/parser/QueryParserConstants.java",
- "src/java/org/apache/solr/parser/QueryParserTokenManager.java",
- "src/java/org/apache/solr/parser/Token.java",
- "src/java/org/apache/solr/parser/TokenMgrError.java"
+ "src/java/org/apache/solr/parser/QueryParser.java",
+ "src/java/org/apache/solr/parser/QueryParserConstants.java",
+ "src/java/org/apache/solr/parser/QueryParserTokenManager.java",
+ "src/java/org/apache/solr/parser/Token.java",
+ "src/java/org/apache/solr/parser/TokenMgrError.java"
break
case ":solr:solr-ref-guide":
// Apply to all example Java sources in the ref-guide
@@ -103,21 +106,22 @@ configure(allprojects) { prj ->
}
// 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 dev-docs/gradle-help/formatting.txt for more info).")
+ tasks.matching {task -> task.name == "spotlessJavaCheck"}.configureEach {
+ it.runToFixMessage.set(
+ "\nIMPORTANT: run the top-level './gradlew tidy' to format code automatically (see dev-docs/gradle-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 == "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 {it.name == "check"}.configureEach {v ->
+ v.dependsOn tasks.matching {it.name == "spotlessCheck"}
}
- tasks.matching { task -> task.name in ["spotlessApply", "spotlessCheck"] }.configureEach { v ->
+ tasks.matching {task -> task.name in ["spotlessApply", "spotlessCheck"]}.configureEach {v ->
v.dependsOn ":checkJdkInternalsExportedToGradle"
}
}
diff --git a/gradle/validation/validate-log-calls.gradle b/gradle/validation/validate-log-calls.gradle
index fb1a81c5403..8bf47502520 100644
--- a/gradle/validation/validate-log-calls.gradle
+++ b/gradle/validation/validate-log-calls.gradle
@@ -34,18 +34,18 @@ import org.apache.tools.ant.BuildException
// See the associated help task "gradlew helpValidateLogCalls"
-configure(subprojects.findAll { it.path.startsWith(':solr') }) {
+configure(subprojects.findAll {it.path.startsWith(':solr')}) {
plugins.withType(JavaPlugin) {
- task validateLogCalls(type: ValidateLogCallsTask) { task ->
+ task validateLogCalls(type: ValidateLogCallsTask) {task ->
description "Checks that log calls are either validated or conform to efficient patterns."
group "verification"
sourceFiles = files(sourceSets*.java)
}
-
+
// Add log validation to per-project checks as well.
check.dependsOn validateLogCalls
- }
+ }
}
class ValidateLogCallsTask extends DefaultTask {
@@ -70,11 +70,13 @@ class ValidateLogCallsTask extends DefaultTask {
}
// Strip all of the comments, things in quotes and the like.
def stripped =
- line.replaceFirst("//.*", " ") // remove comment to EOL. May be fragile due to the possibility of embedded double slashes
+ line.replaceFirst("//.*",
+ " ") // remove comment to EOL. May be fragile due to the possibility of embedded double slashes
.replaceFirst(/.*?\(/, " ") // Get rid of "log.whatever("
.replaceFirst(/\);/, " ") // get rid of the closing ");"
.replaceFirst("/\\*.*?\\*/", " ") // replace embedded comments "/*....*/"
- .replaceAll(/".*?"/, '""') // remove anything between quotes. This is a bit fragile if there are embedded double quotes.
+ .replaceAll(/".*?"/,
+ '""') // remove anything between quotes. This is a bit fragile if there are embedded double quotes.
.replaceAll(/timeLeft\(.*?\)/, " ") // used all over tests, it's benign
.replaceAll(/TimeUnit\..*?\.convert\(.*?\)/, " ") // again, a pattern that's efficient
.replaceAll("\\s", "")
@@ -93,7 +95,7 @@ class ValidateLogCallsTask extends DefaultTask {
}
}
//TODO remove me
- String cause = ""
+ String cause = ""
// Get the level of this log message.
// We don't really care about checking for method calls for WARN and more severe, the presumption
// is that they _should_ always be reported.
@@ -107,7 +109,8 @@ class ValidateLogCallsTask extends DefaultTask {
reportViolation(String.format("Found an unexpected log level: %s, file: %s:%d"
, level, file.getAbsolutePath(), lineNumber))
}
- boolean persnicketyLevel = !(level.equals("fatal") || level.equals("error") || level.equals("warn"))
+ boolean persnicketyLevel = !(level.equals("fatal") || level.equals("error") ||
+ level.equals("warn"))
// Check that previous line isn't an if statement for always-reported log levels.
// There's a convention to declare a member variable for whether a level is enabled and check that rather than
@@ -125,7 +128,8 @@ class ValidateLogCallsTask extends DefaultTask {
def hasParens = m.find()
if (hasParens && prevLineNotIf && persnicketyLevel) {
- cause = "hasParens " + hasParens + " prevLineNotIf " + prevLineNotIf + " pernicketyLevel " + persnicketyLevel
+ cause = "hasParens " + hasParens + " prevLineNotIf " + prevLineNotIf + " pernicketyLevel " +
+ persnicketyLevel
violation = true
}
}
@@ -143,8 +147,13 @@ class ValidateLogCallsTask extends DefaultTask {
violation = true;
}
if (violation) {
- reportViolation(String.format("cause: '%s' Suspicious logging call, Parameterize and possibly surround with 'if (log.is*Enabled) {..}'. Help at: 'gradlew helpValidateLogCalls' %s %s:%d"
- , cause , System.lineSeparator, file.getAbsolutePath(), lineNumber))
+ reportViolation(String.format(
+ "cause: '%s' Suspicious logging call, Parameterize and possibly surround with 'if (log.is*Enabled) {..}'. Help at: 'gradlew helpValidateLogCalls' %s %s:%d"
+ ,
+ cause,
+ System.lineSeparator,
+ file.getAbsolutePath(),
+ lineNumber))
}
return
}
@@ -156,7 +165,8 @@ class ValidateLogCallsTask extends DefaultTask {
if (line.replaceAll("\\s", "").toLowerCase().contains("//nowarn")) {
return
}
- reportViolation("Change the logger name to lower-case 'log' in " + file.name + " " + line + " project" + project)
+ reportViolation("Change the logger name to lower-case 'log' in " + file.name + " " + line +
+ " project" + project)
}
}
@@ -168,7 +178,7 @@ class ValidateLogCallsTask extends DefaultTask {
// We have to assemble line-by-line to get the full log statement. We require that all loggers (except requestLog
// and slowLog) be exactly "log". That will be checked as well.
String prevLine = ""
- file.eachLine { String line ->
+ file.eachLine {String line ->
lineNumber++
checkLogName(file, line)
switch (state) {
@@ -189,7 +199,8 @@ class ValidateLogCallsTask extends DefaultTask {
case 1: // collecting a log line
if (line.replaceFirst("//.*", " ")
.replaceFirst("/\\*.*?\\*/", " ") // replace embedded comments "/*....*/"
- .replaceAll(/".*?"/, '""') // remove anything between quotes. This is a bit fragile if there are embedded double quotes.
+ .replaceAll(/".*?"/,
+ '""') // remove anything between quotes. This is a bit fragile if there are embedded double quotes.
.trim().endsWith(");")) {
state = 2
}
@@ -203,16 +214,16 @@ class ValidateLogCallsTask extends DefaultTask {
// It's just easier to do this here rather than read another line in the switch above.
if (state == 0) {
- // Not collecting a log line
- prevLine = line.toLowerCase();
+ // Not collecting a log line
+ prevLine = line.toLowerCase();
} else if (state == 1) {
- // collecting a logging line.
+ // collecting a logging line.
} else if (state == 2) {
- // We've collected the complete log line.
- checkLine(file, sb.toString(), lineNumber, prevLine)
- state = 0
+ // We've collected the complete log line.
+ checkLine(file, sb.toString(), lineNumber, prevLine)
+ state = 0
} else {
- assert false
+ assert false
}
}
}
@@ -223,12 +234,13 @@ class ValidateLogCallsTask extends DefaultTask {
@TaskAction
def checkLogLines() {
- sourceFiles.each { checkFile(it) }
+ sourceFiles.each {checkFile(it)}
logger.info("Checked: ${sourceFiles.files.size()}")
if (errsFound > 0) {
- throw new BuildException(String.format(Locale.ENGLISH, 'Found %d violations in source files (%s).',
- errsFound, violations.join(', ')));
+ throw new BuildException(String
+ .format(Locale.ENGLISH, 'Found %d violations in source files (%s).',
+ errsFound, violations.join(', ')));
}
}
}
diff --git a/gradle/validation/validate-source-patterns.gradle b/gradle/validation/validate-source-patterns.gradle
index 9c4c93353e0..a164dd75086 100644
--- a/gradle/validation/validate-source-patterns.gradle
+++ b/gradle/validation/validate-source-patterns.gradle
@@ -63,17 +63,17 @@ def extensions = [
// Create source validation task local to each project
allprojects {
- task validateSourcePatterns(type: ValidateSourcePatternsTask) { task ->
+ task validateSourcePatterns(type: ValidateSourcePatternsTask) {task ->
group = 'Verification'
description = 'Validate Source Patterns'
sourceFiles = fileTree(projectDir) {
- extensions.each{
+ extensions.each {
include "**/*.${it}"
}
-
+
// Don't go into child projects (scanned separately).
- childProjects.keySet().each{
+ childProjects.keySet().each {
exclude "${it}/**"
}
@@ -137,33 +137,33 @@ class ValidateSourcePatternsTask extends DefaultTask {
ValidateSourcePatternsTask(ProgressLoggerFactory progressLoggerFactory) {
this.progressLoggerFactory = progressLoggerFactory
}
-
+
@TaskAction
public void check() {
def invalidPatterns = [
- (~$/@author\b/$) : '@author javadoc tag',
- (~$/(?i)\bno(n|)commit\b/$) : 'nocommit',
- (~$/\bTOOD:/$) : 'TOOD instead TODO',
- (~$/\t/$) : 'tabs instead spaces',
- (~$/[\u202A-\u202E\u2066-\u2069]/$) : 'misuse of RTL/LTR (https://trojansource.codes)',
- (~$/\Q/**\E((?:\s)|(?:\*))*\Q{@inheritDoc}\E((?:\s)|(?:\*))*\Q*/\E/$) : '{@inheritDoc} on its own is unnecessary',
- (~$/\$$(?:LastChanged)?Date\b/$) : 'svn keyword',
- (~$/\$$(?:(?:LastChanged)?Revision|Rev)\b/$) : 'svn keyword',
- (~$/\$$(?:LastChangedBy|Author)\b/$) : 'svn keyword',
- (~$/\$$(?:Head)?URL\b/$) : 'svn keyword',
- (~$/\$$Id\b/$) : 'svn keyword',
- (~$/\$$Header\b/$) : 'svn keyword',
- (~$/\$$Source\b/$) : 'svn keyword',
- (~$/^\uFEFF/$) : 'UTF-8 byte order mark',
- (~$/import java\.lang\.\w+;/$) : 'java.lang import is unnecessary'
+ (~$/@author\b/$): '@author javadoc tag',
+ (~$/(?i)\bno(n|)commit\b/$): 'nocommit',
+ (~$/\bTOOD:/$): 'TOOD instead TODO',
+ (~$/\t/$): 'tabs instead spaces',
+ (~$/[\u202A-\u202E\u2066-\u2069]/$): 'misuse of RTL/LTR (https://trojansource.codes)',
+ (~$/\Q/**\E((?:\s)|(?:\*))*\Q{@inheritDoc}\E((?:\s)|(?:\*))*\Q*/\E/$): '{@inheritDoc} on its own is unnecessary',
+ (~$/\$$(?:LastChanged)?Date\b/$): 'svn keyword',
+ (~$/\$$(?:(?:LastChanged)?Revision|Rev)\b/$): 'svn keyword',
+ (~$/\$$(?:LastChangedBy|Author)\b/$): 'svn keyword',
+ (~$/\$$(?:Head)?URL\b/$): 'svn keyword',
+ (~$/\$$Id\b/$): 'svn keyword',
+ (~$/\$$Header\b/$): 'svn keyword',
+ (~$/\$$Source\b/$): 'svn keyword',
+ (~$/^\uFEFF/$): 'UTF-8 byte order mark',
+ (~$/import java\.lang\.\w+;/$): 'java.lang import is unnecessary'
]
def invalidJavaOnlyPatterns = [
- (~$/\n\s*var\s+.*=.*<>.*/$) : 'Diamond operators should not be used with var',
+ (~$/\n\s*var\s+.*=.*<>.*/$): 'Diamond operators should not be used with var',
]
def violations = new TreeSet();
- def reportViolation = { f, name ->
+ def reportViolation = {f, name ->
logger.error('{}: {}', name, f);
violations.add(name);
}
@@ -180,12 +180,17 @@ class ValidateSourcePatternsTask extends DefaultTask {
def extendsLuceneTestCasePattern = ~$/public.*?class.*?extends.*?LuceneTestCase[^\n]*?\n/$;
def validSPINameJavadocTag = ~$/(?s)\s*\*\s*@lucene\.spi\s+\{@value #NAME\}/$;
- def isLicense = { matcher, ratDocument ->
+ def isLicense = {matcher, ratDocument ->
licenseMatcher.reset()
- return lineSplitter.split(matcher.group(1)).any { licenseMatcher.match(ratDocument, it) }
+ return lineSplitter.split(matcher.group(1)).any {licenseMatcher.match(ratDocument, it)}
}
- def checkLicenseHeaderPrecedes = { f, description, contentPattern, commentPattern, text, ratDocument ->
+ def checkLicenseHeaderPrecedes = {f,
+ description,
+ contentPattern,
+ commentPattern,
+ text,
+ ratDocument ->
def contentMatcher = contentPattern.matcher(text);
if (contentMatcher.find()) {
def contentStartPos = contentMatcher.start();
@@ -193,16 +198,17 @@ class ValidateSourcePatternsTask extends DefaultTask {
while (commentMatcher.find()) {
if (isLicense(commentMatcher, ratDocument)) {
if (commentMatcher.start() < contentStartPos) {
- break; // This file is all good, so break loop: license header precedes 'description' definition
+ break;
+ // This file is all good, so break loop: license header precedes 'description' definition
} else {
- reportViolation(f, description+' declaration precedes license header');
+ reportViolation(f, description + ' declaration precedes license header');
}
}
}
}
}
- def checkMockitoAssume = { f, text ->
+ def checkMockitoAssume = {f, text ->
if (text.contains("mockito") && !text.contains("assumeWorkingMockito()")) {
reportViolation(f, 'File uses Mockito but has no assumeWorkingMockito() call')
}
@@ -211,12 +217,12 @@ class ValidateSourcePatternsTask extends DefaultTask {
ProgressLogger progress = progressLoggerFactory.newOperation(this.class)
progress.start(this.name, this.name)
- sourceFiles.each{ f ->
+ sourceFiles.each {f ->
progress.progress("Scanning ${f.name}")
logger.debug('Scanning source file: {}', f);
def text = f.getText('UTF-8');
- invalidPatterns.each { pattern, name ->
+ invalidPatterns.each {pattern, name ->
if (pattern.matcher(text).find()) {
reportViolation(f, name);
}
@@ -226,7 +232,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')) {
@@ -235,26 +241,36 @@ class ValidateSourcePatternsTask extends DefaultTask {
if (text.contains("// nowarn_valid_logger")) {
return
}
- reportViolation(f, 'invalid logging pattern [not private static final, uses static class name]');
+ reportViolation(f,
+ 'invalid logging pattern [not private static final, uses static class name]');
}
if (!validLoggerNamePattern.matcher(text).find()) {
if (text.contains("// nowarn_valid_logger")) {
return
}
- reportViolation(f, 'invalid logger name [log, uses static class name, not specialized logger]')
+ reportViolation(f,
+ 'invalid logger name [log, uses static class name, not specialized logger]')
}
}
// make sure that SPI names of all tokenizers/charfilters/tokenfilters are documented
- 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") &&
+ 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("CharFilterFactory") &&
+ text.contains("extends CharFilterFactory") ||
f.name.contains("FilterFactory") && text.contains("extends TokenFilterFactory"))) {
if (!validSPINameJavadocTag.matcher(text).find()) {
reportViolation(f, 'invalid spi name documentation')
}
}
- checkLicenseHeaderPrecedes(f, 'package', packagePattern, javaCommentPattern, text, ratDocument);
+ checkLicenseHeaderPrecedes(f,
+ 'package',
+ packagePattern,
+ javaCommentPattern,
+ text,
+ ratDocument);
if (f.name.contains("Test")) {
checkMockitoAssume(f, text);
}
@@ -262,10 +278,11 @@ class ValidateSourcePatternsTask extends DefaultTask {
if (f.name.equals("SolrTestCase.java") == false
&& f.name.equals("TestXmlQParser.java") == false) {
if (extendsLuceneTestCasePattern.matcher(text).find()) {
- reportViolation(f, "Solr test cases should extend SolrTestCase rather than LuceneTestCase");
+ reportViolation(f,
+ "Solr test cases should extend SolrTestCase rather than LuceneTestCase");
}
}
- invalidJavaOnlyPatterns.each { pattern,name ->
+ invalidJavaOnlyPatterns.each {pattern, name ->
if (pattern.matcher(text).find()) {
reportViolation(f, name);
}
diff --git a/platform/build.gradle b/platform/build.gradle
index b0a05e07443..7de49677a9a 100644
--- a/platform/build.gradle
+++ b/platform/build.gradle
@@ -19,16 +19,16 @@
// that is inherited by all modules through transitive dependencies (api).
plugins {
- id("java-platform")
+ id("java-platform")
}
dependencies {
- constraints {
- def versionCatalog = rootProject.extensions
- .getByType(VersionCatalogsExtension).named("libs")
- versionCatalog.libraryAliases.forEach { alias ->
- def library = versionCatalog.findLibrary(alias)
- api library.get()
- }
+ constraints {
+ def versionCatalog = rootProject.extensions
+ .getByType(VersionCatalogsExtension).named("libs")
+ versionCatalog.libraryAliases.forEach {alias ->
+ def library = versionCatalog.findLibrary(alias)
+ api library.get()
}
+ }
}
diff --git a/settings.gradle b/settings.gradle
index dfbc62b5654..487fc03cff1 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -16,17 +16,17 @@
*/
pluginManagement {
- repositories {
- mavenCentral()
- gradlePluginPortal()
- }
+ repositories {
+ mavenCentral()
+ gradlePluginPortal()
+ }
- includeBuild("build-tools/build-infra")
+ includeBuild("build-tools/build-infra")
}
plugins {
- id 'com.gradle.develocity' version '3.18.2'
- id 'com.gradle.common-custom-user-data-gradle-plugin' version '2.0.2'
+ id 'com.gradle.develocity' version '3.18.2'
+ id 'com.gradle.common-custom-user-data-gradle-plugin' version '2.0.2'
}
apply from: file('gradle/develocity.gradle')
@@ -71,7 +71,7 @@ include "solr:docker"
def disableUiModuleValue = providers.gradleProperty('disableUiModule').orNull
gradle.ext.withUiModule = disableUiModuleValue == null || disableUiModuleValue != 'true'
if (gradle.ext.withUiModule) {
- include(":solr:ui")
+ include(":solr:ui")
}
// Configures development for joint Lucene/ Solr composite build.
diff --git a/solr/api/build.gradle b/solr/api/build.gradle
index 48da335f472..cd3388260d4 100644
--- a/solr/api/build.gradle
+++ b/solr/api/build.gradle
@@ -25,27 +25,27 @@ apply plugin: 'java-library'
description = 'API - Interfaces and classes used to represent Solrs APIs'
ext {
- jsClientDir = "${buildDir}/generated/js"
- pythonClientDir = "${buildDir}/generated/python"
- openApiSpecDir = "${buildDir}/generated/openapi"
- openApiSpecFile = "${project.openApiSpecDir}/solr-openapi-${version}.json"
+ jsClientDir = "${buildDir}/generated/js"
+ pythonClientDir = "${buildDir}/generated/python"
+ openApiSpecDir = "${buildDir}/generated/openapi"
+ openApiSpecFile = "${project.openApiSpecDir}/solr-openapi-${version}.json"
}
configurations {
- openapiSpec {
- canBeConsumed = true
- canBeResolved = false
- }
- jsClient {
- canBeConsumed = true
- canBeResolved = false
- }
- pythonClient {
- canBeConsumed = true
- canBeResolved = false
- }
-
- swaggerBuild.extendsFrom implementation
+ openapiSpec {
+ canBeConsumed = true
+ canBeResolved = false
+ }
+ jsClient {
+ canBeConsumed = true
+ canBeResolved = false
+ }
+ pythonClient {
+ canBeConsumed = true
+ canBeResolved = false
+ }
+
+ swaggerBuild.extendsFrom implementation
}
resolve {
@@ -60,25 +60,25 @@ resolve {
}
dependencies {
- api platform(project(":platform"))
- swaggerDeps platform(project(":platform"))
- api platform(libs.fasterxml.jackson.bom)
+ api platform(project(":platform"))
+ swaggerDeps platform(project(":platform"))
+ api platform(libs.fasterxml.jackson.bom)
- runtimeOnly libs.slf4j.api
+ runtimeOnly libs.slf4j.api
- implementation libs.jakarta.ws.rsapi
- api libs.fasterxml.jackson.core.annotations
- api libs.swagger3.annotations.jakarta
- implementation libs.semver4j.semver4j
+ implementation libs.jakarta.ws.rsapi
+ api libs.fasterxml.jackson.core.annotations
+ api libs.swagger3.annotations.jakarta
+ implementation libs.semver4j.semver4j
- testImplementation project(':solr:test-framework')
- testImplementation project(':solr:api')
- testImplementation libs.junit.junit
- testImplementation libs.hamcrest.hamcrest
- testImplementation libs.apache.lucene.testframework
- testImplementation libs.fasterxml.jackson.core.databind
+ testImplementation project(':solr:test-framework')
+ testImplementation project(':solr:api')
+ testImplementation libs.junit.junit
+ testImplementation libs.hamcrest.hamcrest
+ testImplementation libs.apache.lucene.testframework
+ testImplementation libs.fasterxml.jackson.core.databind
- swaggerBuild libs.swagger3.jaxrs2.jakarta
+ swaggerBuild libs.swagger3.jaxrs2.jakarta
}
// Non-Java client generation tasks below:
@@ -105,16 +105,16 @@ tasks.withType(org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
}
artifacts {
- // Ensure the OAS is available to other modules who want to generate code (i.e. solrj)
- openapiSpec file(openApiSpecFile), {
- builtBy resolve
- }
-
- // Makes generated clients available to other build modules
- jsClient file(project.jsClientDir), {
- builtBy buildJSClient
- }
- pythonClient file(project.pythonClientDir), {
- builtBy buildPythonClient
- }
+ // Ensure the OAS is available to other modules who want to generate code (i.e. solrj)
+ openapiSpec file(openApiSpecFile), {
+ builtBy resolve
+ }
+
+ // Makes generated clients available to other build modules
+ jsClient file(project.jsClientDir), {
+ builtBy buildJSClient
+ }
+ pythonClient file(project.pythonClientDir), {
+ builtBy buildPythonClient
+ }
}
diff --git a/solr/core/build.gradle b/solr/core/build.gradle
index ea97b09eba6..e99101ba15c 100644
--- a/solr/core/build.gradle
+++ b/solr/core/build.gradle
@@ -61,7 +61,7 @@ dependencies {
permitUnusedDeclared libs.jersey.containers.jettyhttp
implementation libs.jersey.inject.hk2
permitUnusedDeclared libs.jersey.inject.hk2
- implementation (libs.jersey.media.jsonjackson, {
+ implementation(libs.jersey.media.jsonjackson, {
exclude group: "jakarta.xml.bind", module: "jakarta.xml.bind-api"
})
permitUnusedDeclared libs.jersey.media.jsonjackson
@@ -92,7 +92,6 @@ dependencies {
implementation libs.apache.lucene.spatialextras
implementation libs.apache.lucene.suggest
-
// Collections & lang utilities
implementation libs.google.guava
implementation libs.apache.commons.lang3
@@ -100,7 +99,7 @@ dependencies {
implementation libs.commonsio.commonsio
implementation libs.carrotsearch.hppc
- implementation(libs.benmanes.caffeine) { transitive = false }
+ implementation(libs.benmanes.caffeine) {transitive = false}
implementation libs.commonscodec.commonscodec
@@ -136,7 +135,7 @@ dependencies {
implementation(libs.apache.zookeeper.jute) {
exclude group: 'org.apache.yetus', module: 'audience-annotations'
}
- testImplementation variantOf(libs.apache.zookeeper.zookeeper) { classifier 'tests' }
+ testImplementation variantOf(libs.apache.zookeeper.zookeeper) {classifier 'tests'}
// required for instantiating a Zookeeper server (for embedding ZK or running tests)
runtimeOnly libs.xerial.snappy.java
diff --git a/solr/cross-dc-manager/build.gradle b/solr/cross-dc-manager/build.gradle
index e6b120190f2..6d128614612 100644
--- a/solr/cross-dc-manager/build.gradle
+++ b/solr/cross-dc-manager/build.gradle
@@ -96,7 +96,7 @@ task run(type: JavaExec) {
description = 'Run the main class with JavaExecTask'
mainClass = project.ext.mainClass
classpath = sourceSets.main.runtimeClasspath
- systemProperties = ["log4j.configurationFile":"file:conf/log4j2.xml"]
+ systemProperties = ["log4j.configurationFile": "file:conf/log4j2.xml"]
}
jar {
diff --git a/solr/distribution/build.gradle b/solr/distribution/build.gradle
index 8609ffab173..b3e2e6e0bee 100644
--- a/solr/distribution/build.gradle
+++ b/solr/distribution/build.gradle
@@ -27,12 +27,12 @@ plugins {
ext {
releaseDir = file("${buildDir}/release")
- withSignedArtifacts = { ->
+ 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()
- useGpgForSigning = { ->
+ useGpgForSigning = {->
def propValue = propertyOrDefault("useGpg", null)
// Allow -PuseGpg to work as a shorthand for -PuseGpg=true
return propValue != null && (propValue.isBlank() || Boolean.parseBoolean(propValue))
@@ -48,7 +48,6 @@ if (project.ext.useGpgForSigning) {
// Prepare the "source" distribution artifact.
apply from: buildscript.sourceFile.toPath().resolveSibling("source-release.gradle")
-
// Set up the HTML-rendered "changes" distribution artifact by linking to documentation's output.
configurations {
changesHtml
@@ -73,7 +72,7 @@ task computeChecksums(type: buildinfra.checksumClass()) {
tasks.assembleSourceTgz,
fullDistTarTask,
slimDistTarTask
- ].each { dep ->
+ ].each {dep ->
dependsOn dep
files += dep.outputs.files
}
@@ -117,14 +116,13 @@ task prepareGitRev() {
ext.outputFile = file("${buildDir}/.gitrev")
outputs.file(ext.outputFile)
- inputs.property("gitrev", provider { -> rootProject.ext.gitRev })
+ inputs.property("gitrev", provider {-> rootProject.ext.gitRev})
doFirst {
Files.writeString(ext.outputFile.toPath(), rootProject.ext.gitRev, StandardCharsets.UTF_8)
}
}
-
// Assemble everything needed in the release folder structure.
task assembleRelease(type: Sync) {
description "Assemble all Solr artifacts for a release."
@@ -153,21 +151,21 @@ task assembleRelease(type: Sync) {
from slimDistTarTask
from(tasks.computeChecksums, {
- exclude { it.file.getName().contains("openapi") }
+ exclude {it.file.getName().contains("openapi")}
})
from(tasks.computeChecksums, {
- include { it.file.getName().contains("openapi") }
+ include {it.file.getName().contains("openapi")}
into "openApi"
})
// Conditionally, attach signatures of all the release archives.
if (project.ext.withSignedArtifacts) {
from(tasks.signReleaseArchives, {
- exclude { it.file.getName().contains("openapi") }
+ exclude {it.file.getName().contains("openapi")}
})
from(tasks.signReleaseArchives, {
- include { it.file.getName().contains("openapi") }
+ include {it.file.getName().contains("openapi")}
into "openApi"
})
}
@@ -175,12 +173,13 @@ 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 [
- "assembleSourceTgz",
- "assembleRelease",
-]}.all {
+tasks.matching {
+ it.name in [
+ "assembleSourceTgz",
+ "assembleRelease",
+ ]
+}.all {
group "distribution"
}
diff --git a/solr/distribution/source-release.gradle b/solr/distribution/source-release.gradle
index 9e0c11b0dcb..9850f4b0f85 100644
--- a/solr/distribution/source-release.gradle
+++ b/solr/distribution/source-release.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// Prepare the "source" distribution artifact. We use raw git export, no additional complexity needed.
configure(project(":solr:distribution")) {
@@ -29,7 +28,7 @@ configure(project(":solr:distribution")) {
destination = file("${buildDir}/packages/solr-${version}-src.tgz")
}
- inputs.property("git-revision", { -> rootProject.ext.gitRev })
+ inputs.property("git-revision", {-> rootProject.ext.gitRev})
outputs.file destination
doFirst {
diff --git a/solr/docker/build.gradle b/solr/docker/build.gradle
index 79e165d08a4..e29b892594b 100644
--- a/solr/docker/build.gradle
+++ b/solr/docker/build.gradle
@@ -24,38 +24,40 @@ description = 'Solr Docker image'
apply plugin: 'base'
def javaVersion = libs.versions.dockerfile.baseimage.java.get()
// Solr Docker inputs
-def dockerImageSolrDist = "${ -> propertyOrEnvOrDefault("solr.docker.dist", "SOLR_DOCKER_DIST", 'full') }"
+def dockerImageSolrDist = "${-> propertyOrEnvOrDefault("solr.docker.dist", "SOLR_DOCKER_DIST", 'full')}"
def isDistSlim = {String dist -> dist.toLowerCase(Locale.ROOT) == "slim"}
-def isImageSlim = { -> isDistSlim(dockerImageSolrDist) }
+def isImageSlim = {-> isDistSlim(dockerImageSolrDist)}
def distToSuffix = {String dist -> isDistSlim(dist) ? "-slim" : ""}
-def dockerImageDistSuffix = "${ -> distToSuffix(dockerImageSolrDist)}"
-def dockerImageTagSuffix = "${ -> propertyOrEnvOrDefault("solr.docker.imageTagSuffix", "SOLR_DOCKER_IMAGE_TAG_SUFFIX", '')}"
-def dockerImageRepo = "${ -> propertyOrEnvOrDefault("solr.docker.imageRepo", "SOLR_DOCKER_IMAGE_REPO", "apache/solr") }"
-def dockerImageTag = "${ -> propertyOrEnvOrDefault("solr.docker.imageTag", "SOLR_DOCKER_IMAGE_TAG", project.version + dockerImageDistSuffix) }"
-def dockerImageName = "${ -> propertyOrEnvOrDefault("solr.docker.imageName", "SOLR_DOCKER_IMAGE_NAME", "${dockerImageRepo}:${dockerImageTag}${dockerImageTagSuffix}") }"
-def baseDockerImage = "${ -> propertyOrEnvOrDefault("solr.docker.baseImage", "SOLR_DOCKER_BASE_IMAGE", 'eclipse-temurin:' + javaVersion + '-jre-noble') }"
-def dockerImagePlatforms = "${ -> propertyOrEnvOrDefault("solr.docker.platform", "SOLR_DOCKER_PLATFORM", '') }"
-def isMultiPlatform = { -> !dockerImagePlatforms.isEmpty() && dockerImagePlatforms.contains(',') }
-def validatePlatformFormat = { platformValue ->
+def dockerImageDistSuffix = "${-> distToSuffix(dockerImageSolrDist)}"
+def dockerImageTagSuffix = "${-> propertyOrEnvOrDefault("solr.docker.imageTagSuffix", "SOLR_DOCKER_IMAGE_TAG_SUFFIX", '')}"
+def dockerImageRepo = "${-> propertyOrEnvOrDefault("solr.docker.imageRepo", "SOLR_DOCKER_IMAGE_REPO", "apache/solr")}"
+def dockerImageTag = "${-> propertyOrEnvOrDefault("solr.docker.imageTag", "SOLR_DOCKER_IMAGE_TAG", project.version + dockerImageDistSuffix)}"
+def dockerImageName = "${-> propertyOrEnvOrDefault("solr.docker.imageName", "SOLR_DOCKER_IMAGE_NAME", "${dockerImageRepo}:${dockerImageTag}${dockerImageTagSuffix}")}"
+def baseDockerImage = "${-> propertyOrEnvOrDefault("solr.docker.baseImage", "SOLR_DOCKER_BASE_IMAGE", 'eclipse-temurin:' + javaVersion + '-jre-noble')}"
+def dockerImagePlatforms = "${-> propertyOrEnvOrDefault("solr.docker.platform", "SOLR_DOCKER_PLATFORM", '')}"
+def isMultiPlatform = {-> !dockerImagePlatforms.isEmpty() && dockerImagePlatforms.contains(',')}
+def validatePlatformFormat = {platformValue ->
if (!platformValue.isEmpty()) {
def platformPattern = ~/^linux\/[\w-]+(\/[\w-]+)?(,\s*linux\/[\w-]+(\/[\w-]+)?)*$/
if (!platformValue.matches(platformPattern)) {
throw new GradleException("Invalid platform format: ${platformValue}\n" +
- "Platform must be in format 'linux/arch' or 'linux/arch/variant' (comma-separated for multiple).\n" +
- "Examples: 'linux/amd64', 'linux/arm64', 'linux/arm/v7', 'linux/amd64,linux/arm64'")
+ "Platform must be in format 'linux/arch' or 'linux/arch/variant' (comma-separated for multiple).\n" +
+ "Examples: 'linux/amd64', 'linux/arm64', 'linux/arm/v7', 'linux/amd64,linux/arm64'")
}
}
}
-def getSolrTgzConfiguration = { -> isImageSlim() ? configurations.solrSlimTgz : configurations.solrFullTgz }
-def officialDockerImageName = {String dist -> "${ -> propertyOrEnvOrDefault("solr.docker.imageName", "SOLR_DOCKER_IMAGE_NAME", "${dockerImageRepo}-official:${dockerImageTag}${distToSuffix(dist)}${dockerImageTagSuffix}") }" }
+def getSolrTgzConfiguration = {->
+ isImageSlim() ? configurations.solrSlimTgz : configurations.solrFullTgz
+}
+def officialDockerImageName = {String dist -> "${-> propertyOrEnvOrDefault("solr.docker.imageName", "SOLR_DOCKER_IMAGE_NAME", "${dockerImageRepo}-official:${dockerImageTag}${distToSuffix(dist)}${dockerImageTagSuffix}")}"}
-def releaseGpgFingerprint = "${ -> propertyOrDefault('signing.gnupg.keyName',propertyOrDefault('signing.keyId','')) }"
+def releaseGpgFingerprint = "${-> propertyOrDefault('signing.gnupg.keyName', propertyOrDefault('signing.keyId', ''))}"
// Build directory locations
def imageIdFile = "$buildDir/image-id"
def smokeTestOfficial = "$buildDir/smoke-check-official"
-def imageIdFileOfficial = { String dist -> "$smokeTestOfficial/$dist/image-id" }
+def imageIdFileOfficial = {String dist -> "$smokeTestOfficial/$dist/image-id"}
configurations {
packaging {
@@ -143,7 +145,7 @@ buildscript {
classpath libs.commonscodec.commonscodec
}
}
-def checksum = { file ->
+def checksum = {file ->
return new DigestUtils(DigestUtils.sha512Digest).digestAsHex(file).trim()
}
@@ -159,16 +161,15 @@ def getBuildxBuilderInfo = {
if (builderCheckResult.exitValue != 0) {
throw new GradleException("Docker Buildx is not available or no builder is configured.\n" +
- "Please ensure Docker Buildx is installed and create a builder:\n" +
- " docker buildx create --name solr-builder --use\n" +
- "Or use an existing builder:\n" +
- " docker buildx use <builder-name>")
+ "Please ensure Docker Buildx is installed and create a builder:\n" +
+ " docker buildx create --name solr-builder --use\n" +
+ "Or use an existing builder:\n" +
+ " docker buildx use <builder-name>")
}
return builderCheckOutput.toString()
}
-
task assemblePackaging(type: Sync) {
description = 'Assemble docker scripts and Dockerfile for Solr Packaging'
dependsOn configurations.packagingLocal
@@ -192,7 +193,7 @@ task dockerBuild() {
// Ensure that the docker image is rebuilt on build-arg changes or changes in the docker context
inputs.properties([
- baseDockerImage: baseDockerImage
+ baseDockerImage: baseDockerImage
])
var solrTgzConfiguration = isImageSlim() ? configurations.solrSlimTgz : configurations.solrFullTgz
inputs.files(solrTgzConfiguration)
@@ -203,10 +204,10 @@ task dockerBuild() {
exec {
standardInput = solrTgzConfiguration.singleFile.newDataInputStream()
commandLine "docker", "build",
- "-f", "solr-${ -> project.version }${dockerImageDistSuffix}/docker/Dockerfile",
- "--iidfile", imageIdFile,
- "--build-arg", "BASE_IMAGE=${ -> inputs.properties.baseDockerImage}",
- "-"
+ "-f", "solr-${-> project.version}${dockerImageDistSuffix}/docker/Dockerfile",
+ "--iidfile", imageIdFile,
+ "--build-arg", "BASE_IMAGE=${-> inputs.properties.baseDockerImage}",
+ "-"
}
}
@@ -214,9 +215,9 @@ task dockerBuild() {
doLast {
def dockerImageId = file(imageIdFile).text
project.logger.lifecycle("Solr Docker Image Created")
- project.logger.lifecycle("\tID: \t${ -> dockerImageId }")
- project.logger.lifecycle("\tBase Image: \t${ -> baseDockerImage }")
- project.logger.lifecycle("\tSolr Version: \t${ -> project.version }")
+ project.logger.lifecycle("\tID: \t${-> dockerImageId}")
+ project.logger.lifecycle("\tBase Image: \t${-> baseDockerImage}")
+ project.logger.lifecycle("\tSolr Version: \t${-> project.version}")
project.logger.lifecycle("\tSolr Distribution: \t${isImageSlim() ? "Slim" : "Full"}")
}
@@ -230,7 +231,7 @@ task dockerTag(dependsOn: tasks.dockerBuild) {
def dockerImageIdFile = file(imageIdFile)
// Ensure that the docker image is re-tagged if the image ID or desired tag changes
inputs.properties([
- dockerImageName: dockerImageName,
+ dockerImageName: dockerImageName,
])
inputs.file(dockerImageIdFile)
@@ -256,8 +257,13 @@ task testDocker(type: TestDockerImageTask, dependsOn: tasks.dockerBuild) {
outputDir = file("$buildDir/test-results")
// include/exclude options are designed for people who know their customizations will break some tests
- testCasesInclude.value(Arrays.asList(propertyOrEnvOrDefault("solr.docker.tests.include", "SOLR_DOCKER_TESTS_INCLUDE", ",").split(",")))
- var excludeCases = new HashSet(Arrays.asList(propertyOrEnvOrDefault("solr.docker.tests.exclude", "SOLR_DOCKER_TESTS_EXCLUDE", ",").split(",")))
+ testCasesInclude
+ .value(Arrays.asList(propertyOrEnvOrDefault("solr.docker.tests.include",
+ "SOLR_DOCKER_TESTS_INCLUDE",
+ ",").split(",")))
+ var excludeCases = new HashSet(Arrays
+ .asList(propertyOrEnvOrDefault("solr.docker.tests.exclude", "SOLR_DOCKER_TESTS_EXCLUDE", ",")
+ .split(",")))
testCasesExclude.value(excludeCases)
}
@@ -267,8 +273,8 @@ task dockerPush(dependsOn: tasks.dockerTag) {
// Ensure that the docker image is re-pushed if the image ID or tag changes
inputs.properties([
- dockerImageName: dockerImageName,
- dockerImagePlatforms: dockerImagePlatforms
+ dockerImageName: dockerImageName,
+ dockerImagePlatforms: dockerImagePlatforms
])
inputs.file(imageIdFile)
@@ -286,9 +292,9 @@ task dockerPush(dependsOn: tasks.dockerTag) {
def builderInfo = getBuildxBuilderInfo()
// Verify the builder supports the requested platforms (fail fast)
- def requestedPlatforms = platformValue.split(",").collect { it.trim() }
+ def requestedPlatforms = platformValue.split(",").collect {it.trim()}
def missingPlatforms = []
- requestedPlatforms.each { platform ->
+ requestedPlatforms.each {platform ->
// Check for exact platform match - use delimiters instead of word boundaries
// Match platform at start/end or surrounded by commas/spaces
def platformPattern = "(?:^|[,\\s])" + Pattern.quote(platform) + "(?:[,\\s]|\$)"
@@ -301,20 +307,20 @@ task dockerPush(dependsOn: tasks.dockerTag) {
// Extract supported platforms from builder info using matcher
def supportedPlatforms = (builderInfo =~ /linux\/[\w-]+(?:\/[\w-]+)?/).collect().join(', ')
throw new GradleException("Current builder does not support all requested platforms: ${missingPlatforms}\n" +
- "Supported platforms: ${supportedPlatforms}\n" +
- "To add platform support, Install QEMU with proper binfmt support.")
+ "Supported platforms: ${supportedPlatforms}\n" +
+ "To add platform support, Install QEMU with proper binfmt support.")
}
def solrTgzConfiguration = getSolrTgzConfiguration()
exec {
standardInput = solrTgzConfiguration.singleFile.newDataInputStream()
commandLine "docker", "buildx", "build",
- "-f", "solr-${ -> project.version }${dockerImageDistSuffix}/docker/Dockerfile",
- "--platform", platformValue,
- "--build-arg", "BASE_IMAGE=${ -> baseDockerImage}",
- "--tag", dockerImageName,
- "--push",
- "-"
+ "-f", "solr-${-> project.version}${dockerImageDistSuffix}/docker/Dockerfile",
+ "--platform", platformValue,
+ "--build-arg", "BASE_IMAGE=${-> baseDockerImage}",
+ "--tag", dockerImageName,
+ "--push",
+ "-"
}
project.logger.lifecycle("Solr Docker Multi-Platform Image Pushed: \t$dockerImageName")
project.logger.lifecycle("\tPlatforms: \t$platformValue")
@@ -333,10 +339,9 @@ task docker {
dependsOn tasks.dockerBuild, tasks.dockerTag
}
-
ext {
// Filters/Patterns for re-use in multiple "template" related tasks
- commentFilter = { line ->
+ commentFilter = {line ->
if (line.startsWith('#-#')) {
return null;
}
@@ -348,14 +353,14 @@ task createBodySnippetDockerfile(type: Copy) {
from 'templates/Dockerfile.body.template'
into "$buildDir/snippets/"
outputs.file("$buildDir/snippets/Dockerfile.body.snippet")
- rename { name -> name.replace("template","snippet") }
+ rename {name -> name.replace("template", "snippet")}
filteringCharset 'UTF-8'
// NOTE: The only "templating" the Dockerfile.body supports is removing comments.
//
// Any situation where it feel appropriate to add variable substitution should be reconsidered, and probably
// implemented as either a build-arg or as a variable expanded in the header snippets (or both)
- filter( commentFilter )
+ filter(commentFilter)
}
ext {
@@ -364,31 +369,31 @@ ext {
// They may only be used in ARG and FROM lines, via the syntax: '_REPLACE_FOO_'
// where 'FOO' is the key used in 'props' (NOTE the leading and trailing literal '_' characters)
dfLocalDetails = [
- name: 'Local',
- template: 'local',
- desc: 'Dockerfile used to create local Solr docker images directly from Solr release tgz file',
-
- // NOTE: There should be no reason for Dockerfile.local to include unique values
- //
- // Values identical in both Dockerfiles should use consistent names in both templates and
- // be defined in the task creation.
- props: [:]
- ]
- dfOfficialFullDetails = [
- name: 'OfficialFull',
- template: 'official',
- desc: 'Dockerfile used to create official Full Solr docker images published to hub.docker.io',
- props: [
- // NOTE: Only include values here that are distinct and unique to the Official Dockerfiles
+ name: 'Local',
+ template: 'local',
+ desc: 'Dockerfile used to create local Solr docker images directly from Solr release tgz file',
+
+ // NOTE: There should be no reason for Dockerfile.local to include unique values
//
// Values identical in both Dockerfiles should use consistent names in both templates and
- // be defined in the task creation
+ // be defined in the task creation.
+ props: [:]
+ ]
+ dfOfficialFullDetails = [
+ name: 'OfficialFull',
+ template: 'official',
+ desc: 'Dockerfile used to create official Full Solr docker images published to hub.docker.io',
+ props: [
+ // NOTE: Only include values here that are distinct and unique to the Official Dockerfiles
+ //
+ // Values identical in both Dockerfiles should use consistent names in both templates and
+ // be defined in the task creation
- // NOTE: SHA is lazy computed...
- 'SOLR_TGZ_SHA': "${ -> checksum(configurations.solrFullTgz.singleFile) }",
- 'RELEASE_MANAGER_GPG_FINGERPRINT': "${ -> releaseGpgFingerprint}",
- 'SOLR_DIST': ""
- ]
+ // NOTE: SHA is lazy computed...
+ 'SOLR_TGZ_SHA': "${-> checksum(configurations.solrFullTgz.singleFile)}",
+ 'RELEASE_MANAGER_GPG_FINGERPRINT': "${-> releaseGpgFingerprint}",
+ 'SOLR_DIST': ""
+ ]
]
dfOfficialSlimDetails = [
name: 'OfficialSlim',
@@ -401,8 +406,8 @@ ext {
// be defined in the task creation
// NOTE: SHA is lazy computed...
- 'SOLR_TGZ_SHA': "${ -> checksum(configurations.solrSlimTgz.singleFile) }",
- 'RELEASE_MANAGER_GPG_FINGERPRINT': "${ -> releaseGpgFingerprint}",
+ 'SOLR_TGZ_SHA': "${-> checksum(configurations.solrSlimTgz.singleFile)}",
+ 'RELEASE_MANAGER_GPG_FINGERPRINT': "${-> releaseGpgFingerprint}",
'SOLR_DIST': "-slim"
]
]
@@ -420,20 +425,19 @@ These templates can be found in the templates/ directory.
The snippets of each section (header and body) are saved to build/snippets after they are templated and before they are combined.
The final Dockerfiles are merely the snippet headers combined with the snippet body.
*/
-[ dfLocalDetails, dfOfficialFullDetails, dfOfficialSlimDetails ].each{ details ->
- def fileName = "Dockerfile.${ -> details.name.replaceAll("(.)([A-Z])", "\$1-\$2").toLowerCase(Locale.ROOT) }"
+[dfLocalDetails, dfOfficialFullDetails, dfOfficialSlimDetails].each {details ->
+ def fileName = "Dockerfile.${-> details.name.replaceAll("(.)([A-Z])", "\$1-\$2").toLowerCase(Locale.ROOT)}"
def outFile = file("$dockerfilesDirPath/${fileName}")
-
tasks.create("createDockerfile${details.name}", Copy) {
description "Creates ${details.desc}"
def props = [
- // Values defined here should be common (and consistent) across both Dockerfiles
- 'BASE_IMAGE': baseDockerImage,
- 'SOLR_VERSION': "${ -> project.version}",
- * : details.props
- ]
+ // Values defined here should be common (and consistent) across both Dockerfiles
+ 'BASE_IMAGE': baseDockerImage,
+ 'SOLR_VERSION': "${-> project.version}",
+ *: details.props
+ ]
dependsOn tasks.createBodySnippetDockerfile
inputs.properties(props)
@@ -442,19 +446,20 @@ The final Dockerfiles are merely the snippet headers combined with the snippet b
from "templates/Dockerfile.${details.template}.header.template"
into "$buildDir/snippets/"
- rename { fileName + ".header.snippet" }
+ rename {fileName + ".header.snippet"}
filteringCharset 'UTF-8'
- filter( commentFilter )
- filter( { line ->
- if ( line.startsWith("FROM ") || line.startsWith("ARG ") ) {
+ filter(commentFilter)
+ filter({line ->
+ if (line.startsWith("FROM ") || line.startsWith("ARG ")) {
Matcher matcher = project.ext.propReplacePattern.matcher(line);
StringBuilder sb = new StringBuilder();
if (matcher.find()) {
String key = matcher.group(1);
- if (null == key || key.isEmpty() || ( ! props.containsKey(key) ) ) {
- throw new GradleException("Line contains invalid REPLACE variable (" + key + "): " + line);
+ if (null == key || key.isEmpty() || (!props.containsKey(key))) {
+ throw new GradleException("Line contains invalid REPLACE variable (" + key + "): " +
+ line);
}
- matcher.appendReplacement(sb, props.get(key) );
+ matcher.appendReplacement(sb, props.get(key));
}
matcher.appendTail(sb);
return sb.toString();
@@ -463,10 +468,10 @@ The final Dockerfiles are merely the snippet headers combined with the snippet b
})
doLast {
- outFile.withWriter('UTF-8') { writer ->
+ outFile.withWriter('UTF-8') {writer ->
files("$buildDir/snippets/${fileName}.header.snippet",
- "$buildDir/snippets/Dockerfile.body.snippet").each { snippet ->
- snippet.withReader('UTF-8') { reader ->
+ "$buildDir/snippets/Dockerfile.body.snippet").each {snippet ->
+ snippet.withReader('UTF-8') {reader ->
writer << reader
}
}
@@ -477,7 +482,8 @@ The final Dockerfiles are merely the snippet headers combined with the snippet b
assemblePackaging.dependsOn tasks.createDockerfileLocal
tasks.createDockerfileOfficialFull.dependsOn configurations.solrFullTgz // to lazy compute SHA
tasks.createDockerfileOfficialSlim.dependsOn configurations.solrSlimTgz // to lazy compute SHA
-tasks.createDockerfileOfficialSlim.mustRunAfter tasks.createDockerfileOfficialFull // Eliminate a weird warning
+tasks.createDockerfileOfficialSlim.mustRunAfter tasks
+ .createDockerfileOfficialFull // Eliminate a weird warning
task createDockerfileOfficial {
dependsOn tasks.createDockerfileOfficialFull
@@ -486,18 +492,21 @@ task createDockerfileOfficial {
// sanity check...
if (''.equals(releaseGpgFingerprint)) {
- gradle.taskGraph.whenReady { graph ->
- if ( graph.hasTask(tasks.createDockerfileOfficialFull) || graph.hasTask(tasks.createDockerfileOfficialSlim) ) {
- throw new GradleException("No GPG keyName found, please see dev-docs/gradle-help/publishing.txt (GPG key is neccessary to create Dockerfile.official)")
+ gradle.taskGraph.whenReady {graph ->
+ if (graph.hasTask(tasks.createDockerfileOfficialFull) ||
+ graph.hasTask(tasks.createDockerfileOfficialSlim)) {
+ throw new GradleException(
+ "No GPG keyName found, please see dev-docs/gradle-help/publishing.txt (GPG key is neccessary to create Dockerfile.official)")
}
}
}
-[ 'Full', 'Slim' ].each { variant ->
+['Full', 'Slim'].each {variant ->
def lowerVariant = variant.toLowerCase(Locale.ROOT)
tasks.create("testBuildDockerfileOfficial${variant}", Copy) {
- description = "Test 'docker build' works with our generated Dockerfile.official-${lowerVariant} using Mocked URLs"
+ description =
+ "Test 'docker build' works with our generated Dockerfile.official-${lowerVariant} using Mocked URLs"
dependsOn tasks.named("createDockerfileOfficial${variant}")
def mockHttpdHome = file("$smokeTestOfficial/$lowerVariant/mock-httpd-home");
@@ -539,7 +548,10 @@ if (''.equals(releaseGpgFingerprint)) {
def mockServerId = mockServerIdFile.text
def mockServerIpStdOut = new ByteArrayOutputStream()
exec {
- commandLine 'docker', 'inspect', "--format={{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", mockServerId
+ commandLine 'docker',
+ 'inspect',
+ "--format={{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
+ mockServerId
standardOutput = mockServerIpStdOut
}
def mockServerIp = mockServerIpStdOut.toString().trim()
@@ -553,7 +565,9 @@ if (''.equals(releaseGpgFingerprint)) {
downloadHost = "mock-downloads.test.org"
}
exec {
- standardInput = file("${dockerfilesDirPath}/Dockerfile.official-${lowerVariant}").newDataInputStream()
+ standardInput =
+ file("${dockerfilesDirPath}/Dockerfile.official-${lowerVariant}")
+ .newDataInputStream()
commandLine 'docker', 'build',
'--add-host', "${downloadHost}:${mockServerIp}",
'--no-cache', // force fresh downloads from our current network
@@ -574,7 +588,7 @@ if (''.equals(releaseGpgFingerprint)) {
if (mockServerIdFile.exists()) {
def mockServerId = mockServerIdFile.text
try {
- exec { commandLine 'docker', 'stop', mockServerId }
+ exec {commandLine 'docker', 'stop', mockServerId}
} catch (Exception e) {
logger.error("Unable to stop docker container ${mockServerId}", e)
if (null != mainException) {
@@ -601,7 +615,8 @@ task testBuildDockerfileOfficial {
dependsOn tasks.testBuildDockerfileOfficialSlim
}
-task testDockerfileOfficialFull(type: TestDockerImageTask, dependsOn: configurations.dockerOfficialFullSmokeCheckImage) {
+task testDockerfileOfficialFull(type: TestDockerImageTask,
+ dependsOn: configurations.dockerOfficialFullSmokeCheckImage) {
description = 'Smoke Test Full Solr docker image built from the official Dockerfile'
idFile = file(imageIdFileOfficial("Full"))
@@ -613,7 +628,8 @@ task testDockerfileOfficialFull(type: TestDockerImageTask, dependsOn: configurat
testCasesExclude.empty()
}
-task testDockerfileOfficialSlim(type: TestDockerImageTask, dependsOn: configurations.dockerOfficialSlimSmokeCheckImage) {
+task testDockerfileOfficialSlim(type: TestDockerImageTask,
+ dependsOn: configurations.dockerOfficialSlimSmokeCheckImage) {
description = 'Smoke Test Slim Solr docker image built from the official Slim Dockerfile'
idFile = file(imageIdFileOfficial("Slim"))
@@ -659,8 +675,11 @@ abstract class TestDockerImageTask extends DefaultTask {
// NOTE: we explicitly don't use DirectoryProperty here because the way WorkerExecutor serializes the params
// causes weird "wrapped" objects to come back that don't work when you try to call `.getAsFile()` or `.getAsFile().getPath()`
Property<String> getTestName();
+
Property<String> getTestDir();
+
Property<String> getWorkDir();
+
Property<String> getImageId();
}
@@ -703,17 +722,20 @@ abstract class TestDockerImageTask extends DefaultTask {
// no easy way to control the amount of parallelization of the work queue (independent of `org.gradle.workers.max`)
// so the best we can do (simply) is a boolean setting that controls if we `await()` after each `submit()`
def workQueue = getWorkerExecutor().noIsolation();
- def runConcurrentTests = project.propertyOrEnvOrDefault("solr.docker.tests.concurrent", "SOLR_DOCKER_TESTS_CONCURRENT", "false").toBoolean()
+ def runConcurrentTests = project.propertyOrEnvOrDefault("solr.docker.tests.concurrent",
+ "SOLR_DOCKER_TESTS_CONCURRENT",
+ "false").toBoolean()
def imageId = idFile.getAsFile().get().text
// Print information on the image before it is tested
- logger.lifecycle("Testing Solr Image ID: $imageId ${ -> runConcurrentTests ? '(concurrently)' : '(sequentially)'}")
+ logger
+ .lifecycle("Testing Solr Image ID: $imageId ${-> runConcurrentTests ? '(concurrently)' : '(sequentially)'}")
def includes = testCasesInclude.get()
def excludes = testCasesExclude.get()
// "Run" each of the test cases
- sourceDir.eachFile { file ->
+ sourceDir.eachFile {file ->
def testName = file.getName()
def outDir = outputDir.get()
def testCaseWorkDir = outDir.dir(testName)
@@ -723,14 +745,14 @@ abstract class TestDockerImageTask extends DefaultTask {
if (runTest) {
project.mkdir testCaseWorkDir
- def paramSetup = { params ->
+ def paramSetup = {params ->
params.getTestName().set(testName)
params.getTestDir().set(file.getPath())
params.getWorkDir().set(testCaseWorkDir.getAsFile().getPath())
params.getImageId().set(imageId)
}
workQueue.submit(SingleTestAction.class, paramSetup);
- if (! runConcurrentTests) {
+ if (!runConcurrentTests) {
workQueue.await();
}
}
diff --git a/solr/example/build.gradle b/solr/example/build.gradle
index d365fe093c1..9976bf2e424 100644
--- a/solr/example/build.gradle
+++ b/solr/example/build.gradle
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
// I am not convinced packaging of examples should be a separate project... Seems more logical to
// move it to just the packaging project (?). Let's leave it for now though.
diff --git a/solr/modules/extraction/build.gradle b/solr/modules/extraction/build.gradle
index e4ece8dc0e0..c84d9ded709 100644
--- a/solr/modules/extraction/build.gradle
+++ b/solr/modules/extraction/build.gradle
@@ -17,7 +17,8 @@
apply plugin: 'java-library'
-description = 'Solr Integration with Tika for extracting content from binary file formats such as Microsoft Word and Adobe PDF'
+description =
+ 'Solr Integration with Tika for extracting content from binary file formats such as Microsoft Word and Adobe PDF'
ext {
// Disable security manager for extraction module tests
diff --git a/solr/modules/gcs-repository/build.gradle b/solr/modules/gcs-repository/build.gradle
index 635d22d1e85..def8b9740e6 100644
--- a/solr/modules/gcs-repository/build.gradle
+++ b/solr/modules/gcs-repository/build.gradle
@@ -22,35 +22,35 @@ apply plugin: 'java-library'
description = 'GCS Backup Repository'
ext {
- // Use of the security manager is not supported on windows.
- useSecurityManager = !Os.isFamily(Os.FAMILY_WINDOWS)
+ // Use of the security manager is not supported on windows.
+ useSecurityManager = !Os.isFamily(Os.FAMILY_WINDOWS)
}
dependencies {
- implementation platform(project(':platform'))
- api project(':solr:core')
- implementation project(':solr:solrj')
-
- implementation libs.apache.lucene.core
- implementation libs.slf4j.api
-
- implementation platform(libs.google.cloud.bom)
- implementation platform(libs.grpc.bom)
- implementation libs.google.api.gax
- implementation libs.google.auth.oauth2http
- implementation libs.google.auth.credentials
- implementation libs.google.cloud.core
- implementation libs.google.cloud.corehttp
- implementation libs.google.cloud.storage
- implementation libs.threeten.bp
-
- testImplementation project(':solr:test-framework')
- testImplementation libs.apache.lucene.testframework
- testImplementation libs.carrotsearch.randomizedtesting.runner
- testImplementation libs.junit.junit
-
- testImplementation(libs.google.cloud.nio) {
- exclude group: 'javax.inject'
- }
+ implementation platform(project(':platform'))
+ api project(':solr:core')
+ implementation project(':solr:solrj')
+
+ implementation libs.apache.lucene.core
+ implementation libs.slf4j.api
+
+ implementation platform(libs.google.cloud.bom)
+ implementation platform(libs.grpc.bom)
+ implementation libs.google.api.gax
+ implementation libs.google.auth.oauth2http
+ implementation libs.google.auth.credentials
+ implementation libs.google.cloud.core
+ implementation libs.google.cloud.corehttp
+ implementation libs.google.cloud.storage
+ implementation libs.threeten.bp
+
+ testImplementation project(':solr:test-framework')
+ testImplementation libs.apache.lucene.testframework
+ testImplementation libs.carrotsearch.randomizedtesting.runner
+ testImplementation libs.junit.junit
+
+ testImplementation(libs.google.cloud.nio) {
+ exclude group: 'javax.inject'
+ }
}
diff --git a/solr/modules/s3-repository/build.gradle b/solr/modules/s3-repository/build.gradle
index fe2cc7f0748..3a0aa64d39a 100644
--- a/solr/modules/s3-repository/build.gradle
+++ b/solr/modules/s3-repository/build.gradle
@@ -87,7 +87,8 @@ dependencies {
test {
// S3Mock uses Spring Boot under the hood, which tries to do too much auto configuration that we don't want
- environment "spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration"
+ environment "spring.autoconfigure.exclude",
+ "org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration"
environment "spring.jmx.enabled", "false"
// Without this, randomizedtesting will think our tests leak threads (b/c S3Mock's Jetty hasn't bothered to clean up yet)
diff --git a/solr/modules/sql/build.gradle b/solr/modules/sql/build.gradle
index d8ba73eb7bc..c847862f7f5 100644
--- a/solr/modules/sql/build.gradle
+++ b/solr/modules/sql/build.gradle
@@ -52,7 +52,6 @@ dependencies {
testRuntimeOnly project(':solr:modules:analysis-extras')
}
-
// Copy all the test resource files from core to the build/resources/test directory
// of the SQL module so we can avoid duplication of the test resource files like
// schemas and SolrConfigs. This can be improved later by making the test classes
diff --git a/solr/packaging/build.gradle b/solr/packaging/build.gradle
index 33fd9197bb3..0e260f6c9ee 100644
--- a/solr/packaging/build.gradle
+++ b/solr/packaging/build.gradle
@@ -48,8 +48,8 @@ configurations {
}
dependencies {
- project(":solr:modules").childProjects.values().stream().map(project -> project.path).each { module ->
- modules project(path: module, configuration: "packaging")
+ project(":solr:modules").childProjects.values().stream().map {project -> project.path}.each {
+ module -> modules project(path: module, configuration: "packaging")
}
crossDcManager project(path: ":solr:cross-dc-manager", configuration: "packaging")
@@ -93,7 +93,7 @@ distributions {
include "README.txt"
})
- from ('static/lib', {
+ from('static/lib', {
into 'lib'
})
@@ -113,7 +113,7 @@ distributions {
into "docker"
filesMatching([
"scripts/**",
- ]) { copy ->
+ ]) {copy ->
copy.setMode(0755)
}
})
@@ -123,7 +123,7 @@ distributions {
"**/*.sh",
"**/bin/solr",
"**/bin/systemd/solr.service",
- ]) { copy ->
+ ]) {copy ->
copy.setMode(0755)
}
@@ -142,8 +142,8 @@ distributions {
from(configurations.crossDcManager, {
into "cross-dc-manager"
filesMatching([
- "bin/*",
- ]) { copy ->
+ "bin/*",
+ ]) {copy ->
copy.setMode(0755)
}
})
@@ -251,8 +251,8 @@ tasks.register('runDev', JavaExec) {
task downloadBats(type: NpmTask) {
group = 'Build Dependency Download'
args = ["install", "https://github.com/bats-core/bats-core#v${libs.versions.bats.core.get()}",
- "https://github.com/bats-core/bats-assert#v${libs.versions.bats.assert.get()}",
- "https://github.com/bats-core/bats-file#v${libs.versions.bats.file.get()}",
+ "https://github.com/bats-core/bats-assert#v${libs.versions.bats.assert.get()}",
+ "https://github.com/bats-core/bats-file#v${libs.versions.bats.file.get()}",
]
inputs.files("${project.ext.nodeProjectDir}/package.json")
@@ -269,7 +269,8 @@ task integrationTests(type: BatsTask) {
def integrationTestOutput = "$buildDir/test-output"
def solrHome = "$integrationTestOutput/solr-home"
def solrTestFailuresDir = "$integrationTestOutput/failure-snapshots"
- var solrPort = Integer.parseInt((String) project.findProperty('bats.port') ?: System.getProperty("bats.port", "-1"))
+ var solrPort = Integer
+ .parseInt((String) project.findProperty('bats.port') ?: System.getProperty("bats.port", "-1"))
while (solrPort > 64000 || solrPort < 0) { // We need room for +1000 for ZK
try (ServerSocket s = new ServerSocket(0)) {
solrPort = s.getLocalPort()
@@ -289,7 +290,8 @@ task integrationTests(type: BatsTask) {
mkdir solrTestFailuresDir
// TODO - if quiet then don't tee
- standardOutput = new TeeOutputStream(System.out, new FileOutputStream("$integrationTestOutput/test-output.txt"))
+ standardOutput = new TeeOutputStream(System.out,
+ new FileOutputStream("$integrationTestOutput/test-output.txt"))
println("Running BATS tests with Solr base port ${solrPort}")
}
@@ -317,7 +319,7 @@ class BatsTask extends Exec {
@Option(option = "tests", description = "Sets test cases to be included")
public void setTestNamePatterns(List<String> tests) {
// TODO: bats --filter <regex>
- tests.each { testFiles << "$testDir/$it" }
+ tests.each {testFiles << "$testDir/$it"}
}
@Override
@@ -327,8 +329,8 @@ class BatsTask extends Exec {
// Note: tests to run must be listed after all other arguments
// Additional debugging output: -x, --verbose-run
- setArgs(['-T', '--print-output-on-failure', '--report-formatter', 'junit', '--output', "$project.buildDir/test-output"] + (testFiles.empty ? testDir : testFiles))
-
+ setArgs(['-T', '--print-output-on-failure', '--report-formatter', 'junit', '--output', "$project.buildDir/test-output"] +
+ (testFiles.empty ? testDir : testFiles))
super.exec()
}
diff --git a/solr/server/build.gradle b/solr/server/build.gradle
index 132f92ec0f8..a22c084d94b 100644
--- a/solr/server/build.gradle
+++ b/solr/server/build.gradle
@@ -75,7 +75,7 @@ dependencies {
webapp project(path: ":solr:webapp", configuration: "war")
- startJar(variantOf(libs.eclipse.jetty.start) { classifier 'shaded' }, {
+ startJar(variantOf(libs.eclipse.jetty.start) {classifier 'shaded'}, {
transitive false
})
@@ -107,13 +107,13 @@ task assemblePackaging(type: Sync) {
// Allow duplicates to overwrite previous files
duplicatesStrategy = DuplicatesStrategy.INCLUDE
// Rename dev files in development
- rename { String fileName -> fileName.replace("-dev.xml", ".xml") }
+ rename {String fileName -> fileName.replace("-dev.xml", ".xml")}
// Exclude production configurations
exclude "**/*-prod.xml"
} else {
// Rename prod files in production
- rename { String fileName -> fileName.replace("-prod.xml", ".xml") }
+ rename {String fileName -> fileName.replace("-prod.xml", ".xml")}
// Exclude dev configurations
exclude "**/*-dev.xml"
@@ -121,7 +121,8 @@ task assemblePackaging(type: Sync) {
})
// Add in the intersection of serverLib and solrCore
- from(configurations.libExt + (configurations.serverLib - (configurations.serverLib - configurations.solrCore)), {
+ from(configurations.libExt +
+ (configurations.serverLib - (configurations.serverLib - configurations.solrCore)), {
into "lib/ext"
})
@@ -129,12 +130,12 @@ task assemblePackaging(type: Sync) {
into "lib/"
})
- from { project.configurations.startJar.singleFile } {
- rename { file -> 'start.jar' }
+ from {project.configurations.startJar.singleFile} {
+ rename {file -> 'start.jar'}
}
dependsOn configurations.webapp
- from( { zipTree(configurations.webapp.asPath) }, {
+ from({zipTree(configurations.webapp.asPath)}, {
into "solr-webapp/webapp"
})
diff --git a/solr/solr-ref-guide/build.gradle b/solr/solr-ref-guide/build.gradle
index 3876671f080..9771a220e07 100644
--- a/solr/solr-ref-guide/build.gradle
+++ b/solr/solr-ref-guide/build.gradle
@@ -25,179 +25,188 @@ description = 'Solr Reference Guide'
Antora Logic - Building the ref-guide
*/
-def officialSiteIncludePrerelease = propertyOrEnvOrDefault("refguide.official.includePrereleaseVersions", "SOLR_REF_GUIDE_OFFICIAL_INCLUDE_PRERELEASE", "false").toBoolean()
-
-def buildLocalUI = propertyOrEnvOrDefault("refguide.buildLocalUI", "SOLR_REF_GUIDE_BUILD_LOCAL_UI", "false").toBoolean()
-def isBranchReleased = propertyOrEnvOrDefault("refguide.isBranchReleased", "SOLR_REF_GUIDE_IS_BRANCH_RELEASED", "false").toBoolean()
+def officialSiteIncludePrerelease = propertyOrEnvOrDefault(
+ "refguide.official.includePrereleaseVersions",
+ "SOLR_REF_GUIDE_OFFICIAL_INCLUDE_PRERELEASE",
+ "false").toBoolean()
+
+def buildLocalUI = propertyOrEnvOrDefault("refguide.buildLocalUI",
+ "SOLR_REF_GUIDE_BUILD_LOCAL_UI",
+ "false").toBoolean()
+def isBranchReleased = propertyOrEnvOrDefault("refguide.isBranchReleased",
+ "SOLR_REF_GUIDE_IS_BRANCH_RELEASED",
+ "false").toBoolean()
// This escapes strings inside YAML templates
// WARNING: Strings in YAML must use single quotes for this to work correctly!
// Double quotes in YAML can't be used as this requires more complicated
// escaping, see spec: https://yaml.org/spec/1.2.2/#732-single-quoted-style
def escapeYamlSingleQuotesString(props) {
- return props.collectEntries{k, v -> [k, v.toString().replace("'","''")]}
+ return props.collectEntries {k, v -> [k, v.toString().replace("'", "''")]}
}
// Attach building the ref guide to standard convention tasks. This
// can be optionally turned off (see SOLR-15670).
var defaultRefGuideInclude = file("${rootDir}/.git").exists()
-if (propertyOrEnvOrDefault('refguide.include', 'SOLR_REF_GUIDE_INCLUDE', "${defaultRefGuideInclude}").toBoolean()) {
- check.dependsOn 'checkSiteLinks'
- assemble.dependsOn 'buildLocalSite'
+if (propertyOrEnvOrDefault('refguide.include',
+ 'SOLR_REF_GUIDE_INCLUDE',
+ "${defaultRefGuideInclude}").toBoolean()) {
+ check.dependsOn 'checkSiteLinks'
+ assemble.dependsOn 'buildLocalSite'
}
configurations {
- refGuide
- officialPlaybook
- localPlaybook
- localJavadocs
+ refGuide
+ officialPlaybook
+ localPlaybook
+ localJavadocs
}
dependencies {
- localJavadocs project(path: ":solr:documentation", configuration: 'javadocs')
- localJavadocs project(path: ":solr:documentation", configuration: 'site')
+ localJavadocs project(path: ":solr:documentation", configuration: 'javadocs')
+ localJavadocs project(path: ":solr:documentation", configuration: 'site')
}
ext {
- siteDir = "${buildDir}/site"
- antoraConfigBuildDir = "${buildDir}/antora-config"
- playbooksDir = "${project.ext.antoraConfigBuildDir}/playbooks"
- localAntoraYaml = "${project.ext.antoraConfigBuildDir}/antora.yml"
- siteStagingDir = "${buildDir}/site-staging"
- uiBuildDir = "${buildDir}/ui"
- playbookTemplate = "playbook.template.yml"
- localPlaybook = "local-playbook.yml"
- officialPlaybook = "official-playbook.yml"
+ siteDir = "${buildDir}/site"
+ antoraConfigBuildDir = "${buildDir}/antora-config"
+ playbooksDir = "${project.ext.antoraConfigBuildDir}/playbooks"
+ localAntoraYaml = "${project.ext.antoraConfigBuildDir}/antora.yml"
+ siteStagingDir = "${buildDir}/site-staging"
+ uiBuildDir = "${buildDir}/ui"
+ playbookTemplate = "playbook.template.yml"
+ localPlaybook = "local-playbook.yml"
+ officialPlaybook = "official-playbook.yml"
}
/*
Generating the Antora and Playbook YAML files
*/
task buildLocalAntoraYaml {
- group = 'Site - Local'
- description "Creates a local antora.yml with all variables populated."
+ group = 'Site - Local'
+ description "Creates a local antora.yml with all variables populated."
- def templateYaml = "antora.template.yml"
+ def templateYaml = "antora.template.yml"
- inputs.file(templateYaml)
- outputs.file(project.ext.localAntoraYaml)
+ inputs.file(templateYaml)
+ outputs.file(project.ext.localAntoraYaml)
- def splitVersion = version.toString().split("\\p{Punct}")
- def displayVersion = "${splitVersion[0]}.${splitVersion[1]}"
- def prerelease = false
- if (!isBranchReleased) {
- if (splitVersion[1] == "0") {
- prerelease = "-alpha"
- }
- else {
- prerelease = "-beta"
- }
- displayVersion += prerelease
+ def splitVersion = version.toString().split("\\p{Punct}")
+ def displayVersion = "${splitVersion[0]}.${splitVersion[1]}"
+ def prerelease = false
+ if (!isBranchReleased) {
+ if (splitVersion[1] == "0") {
+ prerelease = "-alpha"
+ } else {
+ prerelease = "-beta"
}
- def props = [
- solr_version : "${splitVersion[0]}.${splitVersion[1]}.${splitVersion[2]}",
- solr_version_major : splitVersion[0],
- solr_version_minor : splitVersion[1],
- solr_version_patch : splitVersion[2],
- displayVersion : displayVersion,
- prerelease : prerelease,
- ]
+ displayVersion += prerelease
+ }
+ def props = [
+ solr_version: "${splitVersion[0]}.${splitVersion[1]}.${splitVersion[2]}",
+ solr_version_major: splitVersion[0],
+ solr_version_minor: splitVersion[1],
+ solr_version_patch: splitVersion[2],
+ displayVersion: displayVersion,
+ prerelease: prerelease,
+ ]
+ props.putAll([
+ solr_javadocs_link: "https://solr.apache.org/docs/${props.solr_version.replace(".", "_")}",
+ lucene_javadocs_link: project(':solr:documentation').luceneDocUrl,
+ ])
+
+ doLast {
+ // Set these dependency versions as lazy gstrings so that they're resolved after evaluation.
+ // These variable names must use underscores, not dashes or periods.
+ // Modifying this list also requires modifying `antora.template.yml`
props.putAll([
- solr_javadocs_link : "https://solr.apache.org/docs/${props.solr_version.replace(".", "_")}",
- lucene_javadocs_link : project(':solr:documentation').luceneDocUrl,
- ])
-
- doLast {
- // Set these dependency versions as lazy gstrings so that they're resolved after evaluation.
- // These variable names must use underscores, not dashes or periods.
- // Modifying this list also requires modifying `antora.template.yml`
- props.putAll([
- ["dep_version_commons_codec", libs.versions.commons.codec],
- ["dep_version_log4j", libs.versions.apache.log4j],
- ["dep_version_opennlp", libs.versions.apache.opennlp],
- ["dep_version_tika", libs.versions.apache.tika],
- ["dep_version_zookeeper", libs.versions.apache.zookeeper],
- ["dep_version_opentelemetry", libs.versions.opentelemetry.asProvider()],
- ].collectEntries { propKey, dependencyVersion ->
- [propKey, "${-> dependencyVersion.get()}"] })
- props["dep_version_lucene"] = "${ -> luceneBaseVersionProvider.get()}"
-
- copy {
- from(templateYaml) {
- rename {
- "antora.yml"
- }
- }
- into project.ext.antoraConfigBuildDir
-
- expand(escapeYamlSingleQuotesString(props))
+ ["dep_version_commons_codec", libs.versions.commons.codec],
+ ["dep_version_log4j", libs.versions.apache.log4j],
+ ["dep_version_opennlp", libs.versions.apache.opennlp],
+ ["dep_version_tika", libs.versions.apache.tika],
+ ["dep_version_zookeeper", libs.versions.apache.zookeeper],
+ ["dep_version_opentelemetry", libs.versions.opentelemetry.asProvider()],
+ ].collectEntries {propKey, dependencyVersion ->
+ [propKey, "${-> dependencyVersion.get()}"]
+ })
+ props["dep_version_lucene"] = "${-> luceneBaseVersionProvider.get()}"
+
+ copy {
+ from(templateYaml) {
+ rename {
+ "antora.yml"
}
+ }
+ into project.ext.antoraConfigBuildDir
+
+ expand(escapeYamlSingleQuotesString(props))
}
- inputs.properties(props)
+ }
+ inputs.properties(props)
}
task buildLocalAntoraPlaybookYaml(type: Copy) {
- group = 'Site - Local'
- description "Creates ${project.ext.localPlaybook} to build and test the site locally"
+ group = 'Site - Local'
+ description "Creates ${project.ext.localPlaybook} to build and test the site locally"
- from(project.ext.playbookTemplate) {
- rename {
- project.ext.localPlaybook
- }
+ from(project.ext.playbookTemplate) {
+ rename {
+ project.ext.localPlaybook
}
- into project.ext.playbooksDir
-
- def props = [
- 'site_url' : "",
- 'redirect_facility' : "static",
- 'source_url' : project.rootDir,
- 'source_branches' : "HEAD",
- 'start_path' : project.rootDir.relativePath(file(project.ext.siteStagingDir)),
- 'site_dir' : "./" + file(project.ext.siteStagingDir).relativePath(file(project.ext.siteDir)),
- ]
-
- expand(escapeYamlSingleQuotesString(props))
- inputs.properties(props)
+ }
+ into project.ext.playbooksDir
+
+ def props = [
+ 'site_url': "",
+ 'redirect_facility': "static",
+ 'source_url': project.rootDir,
+ 'source_branches': "HEAD",
+ 'start_path': project.rootDir.relativePath(file(project.ext.siteStagingDir)),
+ 'site_dir': "./" + file(project.ext.siteStagingDir).relativePath(file(project.ext.siteDir)),
+ ]
+
+ expand(escapeYamlSingleQuotesString(props))
+ inputs.properties(props)
}
task buildOfficialAntoraPlaybookYaml(type: Copy) {
- group = 'Site - Official'
- description "Creates ${project.ext.officialPlaybook} to build the official Solr ref-guide"
-
- from(project.ext.playbookTemplate) {
- rename {
- project.ext.officialPlaybook
- }
- }
- into project.ext.playbooksDir
+ group = 'Site - Official'
+ description "Creates ${project.ext.officialPlaybook} to build the official Solr ref-guide"
- def branches = ["branch_*"]
- if (officialSiteIncludePrerelease) {
- branches.add("main")
- } else {
- branches.add("\"!branch_*x\"")
+ from(project.ext.playbookTemplate) {
+ rename {
+ project.ext.officialPlaybook
}
-
- def props = [
- 'site_url' : "https://solr.apache.org/guide",
- 'redirect_facility' : "httpd",
- 'source_url' : "https://github.com/apache/solr.git",
- 'source_branches' : branches,
- 'start_path' : 'solr/solr-ref-guide',
- 'site_dir' : "./" + file(project.ext.playbooksDir).relativePath(file(project.ext.siteDir)),
- ]
-
- expand(escapeYamlSingleQuotesString(props))
- inputs.properties(props)
+ }
+ into project.ext.playbooksDir
+
+ def branches = ["branch_*"]
+ if (officialSiteIncludePrerelease) {
+ branches.add("main")
+ } else {
+ branches.add("\"!branch_*x\"")
+ }
+
+ def props = [
+ 'site_url': "https://solr.apache.org/guide",
+ 'redirect_facility': "httpd",
+ 'source_url': "https://github.com/apache/solr.git",
+ 'source_branches': branches,
+ 'start_path': 'solr/solr-ref-guide',
+ 'site_dir': "./" + file(project.ext.playbooksDir).relativePath(file(project.ext.siteDir)),
+ ]
+
+ expand(escapeYamlSingleQuotesString(props))
+ inputs.properties(props)
}
dependencies {
- localPlaybook files("${project.ext.playbooksDir}/${project.ext.localPlaybook}") {
- builtBy tasks.buildLocalAntoraPlaybookYaml
- }
- officialPlaybook files("${project.ext.playbooksDir}/${project.ext.officialPlaybook}") {
- builtBy tasks.buildOfficialAntoraPlaybookYaml
- }
+ localPlaybook files("${project.ext.playbooksDir}/${project.ext.localPlaybook}") {
+ builtBy tasks.buildLocalAntoraPlaybookYaml
+ }
+ officialPlaybook files("${project.ext.playbooksDir}/${project.ext.officialPlaybook}") {
+ builtBy tasks.buildOfficialAntoraPlaybookYaml
+ }
}
/*
@@ -205,115 +214,116 @@ dependencies {
*/
task downloadAntoraCli(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "@antora/cli@${libs.versions.antora.asProvider().get()}"]
+ group = 'Build Dependency Download'
+ args = ["install", "@antora/cli@${libs.versions.antora.asProvider().get()}"]
- inputs.property("Antora version", libs.versions.antora.asProvider().get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/cli")
+ inputs.property("Antora version", libs.versions.antora.asProvider().get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/cli")
}
task downloadAntoraSiteGenerator(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "@antora/site-generator-default@${libs.versions.antora.asProvider().get()}"]
+ group = 'Build Dependency Download'
+ args = ["install", "@antora/site-generator-default@${libs.versions.antora.asProvider().get()}"]
- inputs.property("Antora version", libs.versions.antora.asProvider().get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/site-generator-default")
+ inputs.property("Antora version", libs.versions.antora.asProvider().get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/site-generator-default")
}
task downloadAntoraLunrExtension(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "@antora/lunr-extension@${libs.versions.antora.lunr.extension.get()}"]
+ group = 'Build Dependency Download'
+ args = ["install", "@antora/lunr-extension@${libs.versions.antora.lunr.extension.get()}"]
- inputs.property("Antora lunr-extension version", libs.versions.antora.lunr.extension.get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/lunr-extension")
+ inputs.property("Antora lunr-extension version", libs.versions.antora.lunr.extension.get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/lunr-extension")
}
task downloadAsciidoctorMathjaxExtension(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "@djencks/asciidoctor-mathjax@${libs.versions.asciidoctor.mathjax.get()}"]
+ group = 'Build Dependency Download'
+ args = ["install", "@djencks/asciidoctor-mathjax@${libs.versions.asciidoctor.mathjax.get()}"]
- inputs.property("asciidoctor-mathjax version", libs.versions.asciidoctor.mathjax.get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/@djencks/asciidoctor-mathjax")
+ inputs.property("asciidoctor-mathjax version", libs.versions.asciidoctor.mathjax.get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/@djencks/asciidoctor-mathjax")
}
task downloadAsciidoctorTabsExtension(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "-D", "@asciidoctor/tabs@${libs.versions.asciidoctor.tabs.get()}"]
+ group = 'Build Dependency Download'
+ args = ["install", "-D", "@asciidoctor/tabs@${libs.versions.asciidoctor.tabs.get()}"]
- inputs.property("asciidoctor-tabs version", libs.versions.asciidoctor.tabs.get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/@asciidoctor/tabs")
+ inputs.property("asciidoctor-tabs version", libs.versions.asciidoctor.tabs.get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/@asciidoctor/tabs")
}
task downloadAntora {
- group = 'Build Dependency Download'
- description "Download all Antora build dependencies for site generation."
-
- dependsOn tasks.downloadAntoraCli
- dependsOn tasks.downloadAntoraSiteGenerator
- dependsOn tasks.downloadAntoraLunrExtension
- dependsOn tasks.downloadAsciidoctorMathjaxExtension
- dependsOn tasks.downloadAsciidoctorTabsExtension
+ group = 'Build Dependency Download'
+ description "Download all Antora build dependencies for site generation."
+
+ dependsOn tasks.downloadAntoraCli
+ dependsOn tasks.downloadAntoraSiteGenerator
+ dependsOn tasks.downloadAntoraLunrExtension
+ dependsOn tasks.downloadAsciidoctorMathjaxExtension
+ dependsOn tasks.downloadAsciidoctorTabsExtension
}
task downloadLinkValidator(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "link-checker@${libs.versions.link.checker.get()}"]
+ group = 'Build Dependency Download'
+ args = ["install", "link-checker@${libs.versions.link.checker.get()}"]
- inputs.property("link-checker version", libs.versions.link.checker.get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/link-checker")
+ inputs.property("link-checker version", libs.versions.link.checker.get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/link-checker")
}
task downloadDefaultUITemplate(type: NpmTask) {
- group = 'Build Dependency Download'
- args = ["install", "gitlab:antora/antora-ui-default#${libs.versions.antora.default.ui.get()}", "--include=dev"]
+ group = 'Build Dependency Download'
+ args =
+ ["install", "gitlab:antora/antora-ui-default#${libs.versions.antora.default.ui.get()}", "--include=dev"]
- inputs.property("Antora default-ui version", libs.versions.antora.default.ui.get())
- outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/ui-default")
+ inputs.property("Antora default-ui version", libs.versions.antora.default.ui.get())
+ outputs.dir("${project.ext.nodeProjectDir}/node_modules/@antora/ui-default")
}
task startUIBuildDir(type: Copy) {
- group = 'Site - UI'
- dependsOn tasks.downloadDefaultUITemplate
-
- // Copy the antora latest default ui into the root folder, to mimic a new checkout of the default ui
- with {
- from "${project.ext.nodeProjectDir}/node_modules/@antora/ui-default"
- duplicatesStrategy = 'EXCLUDE'
- }
-
- // Overwrite the parts of the UI that we have changed.
- from("${projectDir}/ui-src") {
- into "src"
- }
- duplicatesStrategy = 'INCLUDE'
-
- into project.ext.uiBuildDir
+ group = 'Site - UI'
+ dependsOn tasks.downloadDefaultUITemplate
+
+ // Copy the antora latest default ui into the root folder, to mimic a new checkout of the default ui
+ with {
+ from "${project.ext.nodeProjectDir}/node_modules/@antora/ui-default"
+ duplicatesStrategy = 'EXCLUDE'
+ }
+
+ // Overwrite the parts of the UI that we have changed.
+ from("${projectDir}/ui-src") {
+ into "src"
+ }
+ duplicatesStrategy = 'INCLUDE'
+
+ into project.ext.uiBuildDir
}
task setupUIBuildDir(type: NpmTask) {
- group = 'Site - UI'
- dependsOn tasks.startUIBuildDir
- workingDir = file(project.ext.uiBuildDir)
- args = ["install"]
+ group = 'Site - UI'
+ dependsOn tasks.startUIBuildDir
+ workingDir = file(project.ext.uiBuildDir)
+ args = ["install"]
- inputs.files("${project.ext.uiBuildDir}/package.json")
- outputs.dir("${project.ext.uiBuildDir}/node_modules/")
+ inputs.files("${project.ext.uiBuildDir}/package.json")
+ outputs.dir("${project.ext.uiBuildDir}/node_modules/")
}
// Note that Gulp must be installed in the UI Build Directory, not our project node_modules
task downloadGulp(type: NpmTask) {
- group = 'Build Dependency Download'
- dependsOn tasks.startUIBuildDir
-
- args = ["install", "gulp-cli@${libs.versions.gulp.cli.get()}", "--legacy-peer-deps"]
- execOverrides {
- // The it variable contains the `ExecSpec`
- workingDir = project.ext.uiBuildDir
- }
-
- inputs.property("Antora version", libs.versions.antora.asProvider().get())
- inputs.property("Gulp CLI version", libs.versions.gulp.cli.get())
- outputs.dir("${project.ext.uiBuildDir}/node_modules/")
+ group = 'Build Dependency Download'
+ dependsOn tasks.startUIBuildDir
+
+ args = ["install", "gulp-cli@${libs.versions.gulp.cli.get()}", "--legacy-peer-deps"]
+ execOverrides {
+ // The it variable contains the `ExecSpec`
+ workingDir = project.ext.uiBuildDir
+ }
+
+ inputs.property("Antora version", libs.versions.antora.asProvider().get())
+ inputs.property("Gulp CLI version", libs.versions.gulp.cli.get())
+ outputs.dir("${project.ext.uiBuildDir}/node_modules/")
}
/*
@@ -321,213 +331,213 @@ task downloadGulp(type: NpmTask) {
*/
task buildUIBundle(type: NpxTask) {
- group = 'Site - UI'
- description "Creates a local UI bundle using the 'ui-src' directory. This can be used to preview UI changes with a local or official ref-guide build."
-
- dependsOn tasks.setupUIBuildDir
- dependsOn tasks.downloadGulp
-
- command = "gulp"
-
- args = [
- "bundle",
- ]
- execOverrides {
- // The it variable contains the `ExecSpec`
- workingDir = project.ext.uiBuildDir
- }
-
- doLast {
- copy {
- from "${project.ext.uiBuildDir}/build/ui-bundle.zip"
- into "${buildDir}/dist"
- }
+ group = 'Site - UI'
+ description "Creates a local UI bundle using the 'ui-src' directory. This can be used to preview UI changes with a local or official ref-guide build."
+
+ dependsOn tasks.setupUIBuildDir
+ dependsOn tasks.downloadGulp
+
+ command = "gulp"
+
+ args = [
+ "bundle",
+ ]
+ execOverrides {
+ // The it variable contains the `ExecSpec`
+ workingDir = project.ext.uiBuildDir
+ }
+
+ doLast {
+ copy {
+ from "${project.ext.uiBuildDir}/build/ui-bundle.zip"
+ into "${buildDir}/dist"
}
+ }
- inputs.files(fileTree("${project.ext.uiBuildDir}/src"))
- outputs.file("${buildDir}/dist/ui-bundle.zip")
+ inputs.files(fileTree("${project.ext.uiBuildDir}/src"))
+ outputs.file("${buildDir}/dist/ui-bundle.zip")
- doLast {
- project.logger.lifecycle("The generated ui-bundle.zip can be found at:")
- project.logger.lifecycle("\t${buildDir}/dist/ui-bundle.zip")
- }
+ doLast {
+ project.logger.lifecycle("The generated ui-bundle.zip can be found at:")
+ project.logger.lifecycle("\t${buildDir}/dist/ui-bundle.zip")
+ }
}
task setupLocalSiteStagingDir(type: Sync) {
- group = 'Site - Local'
- description "Creates a staging directory to build the local ref-guide."
-
- dependsOn tasks.buildLocalAntoraYaml
- dependsOn configurations.localPlaybook
-
- from(projectDir) {
- include "modules/**"
- }
- from project.ext.localAntoraYaml
- from(project.ext.playbooksDir) {
- include project.ext.localPlaybook
- rename {
- "playbook.yml"
- }
+ group = 'Site - Local'
+ description "Creates a staging directory to build the local ref-guide."
+
+ dependsOn tasks.buildLocalAntoraYaml
+ dependsOn configurations.localPlaybook
+
+ from(projectDir) {
+ include "modules/**"
+ }
+ from project.ext.localAntoraYaml
+ from(project.ext.playbooksDir) {
+ include project.ext.localPlaybook
+ rename {
+ "playbook.yml"
}
+ }
- into project.ext.siteStagingDir
+ into project.ext.siteStagingDir
}
task buildLocalAntoraSite(type: NpxTask) {
- group = 'Site - Local'
- description "Creates a local build of the ref-guide."
-
- dependsOn tasks.downloadAntora
- dependsOn tasks.setupLocalSiteStagingDir
-
- command = "antora"
-
- // Use a local build of the Lucene and Solr javadocs for a local refGuide
- def extraArgs = [
- // This attribute should not include ":link", the other 2 should
- // This attribute should also not be relative, because it is used in multiple path directories in the site
- "--attribute", "page-solr-javadocs=${project(':solr:documentation').docroot.toURI().toASCIIString()}",
- "--attribute", "solr-javadocs=link:../../../${file(project.ext.siteDir).relativePath(project(':solr:documentation').docroot)}",
- "--attribute", "lucene-javadocs=link:../../../${file(project.ext.siteDir).relativePath(project(':solr:documentation').luceneDocsDir)}"
- ]
-
- if (buildLocalUI) {
- dependsOn tasks.buildUIBundle
- extraArgs.addAll([
- "--ui-bundle-url", "${buildDir}/dist/ui-bundle.zip"
- ])
- inputs.files("${buildDir}/dist/ui-bundle.zip")
- }
-
- args = [
- "${project.ext.siteStagingDir}/playbook.yml",
- "--fetch"
- ] + extraArgs
-
- // Configure HTTP request timeout via preload script to prevent timeout errors
- // when downloading UI bundle from slow networks (especially in CI)
- def nodeOptions = "--require ${projectDir}/increase-request-timeout.js"
-
- environment = [
- "SITE_SEARCH_ENABLED": "true",
- "MATOMO_ENABLED": "false",
- "NODE_OPTIONS": nodeOptions,
- "HTTP_REQUEST_TIMEOUT_MS": "60000" // 60 seconds timeout
- ]
-
- inputs.files(fileTree(project.ext.siteStagingDir))
- inputs.property("Antora version", libs.versions.antora.asProvider().get())
- outputs.dir(project.ext.siteDir)
+ group = 'Site - Local'
+ description "Creates a local build of the ref-guide."
+
+ dependsOn tasks.downloadAntora
+ dependsOn tasks.setupLocalSiteStagingDir
+
+ command = "antora"
+
+ // Use a local build of the Lucene and Solr javadocs for a local refGuide
+ def extraArgs = [
+ // This attribute should not include ":link", the other 2 should
+ // This attribute should also not be relative, because it is used in multiple path directories in the site
+ "--attribute", "page-solr-javadocs=${project(':solr:documentation').docroot.toURI().toASCIIString()}",
+ "--attribute", "solr-javadocs=link:../../../${file(project.ext.siteDir).relativePath(project(':solr:documentation').docroot)}",
+ "--attribute", "lucene-javadocs=link:../../../${file(project.ext.siteDir).relativePath(project(':solr:documentation').luceneDocsDir)}"
+ ]
+
+ if (buildLocalUI) {
+ dependsOn tasks.buildUIBundle
+ extraArgs.addAll([
+ "--ui-bundle-url", "${buildDir}/dist/ui-bundle.zip"
+ ])
+ inputs.files("${buildDir}/dist/ui-bundle.zip")
+ }
+
+ args = [
+ "${project.ext.siteStagingDir}/playbook.yml",
+ "--fetch"
+ ] + extraArgs
+
+ // Configure HTTP request timeout via preload script to prevent timeout errors
+ // when downloading UI bundle from slow networks (especially in CI)
+ def nodeOptions = "--require ${projectDir}/increase-request-timeout.js"
+
+ environment = [
+ "SITE_SEARCH_ENABLED": "true",
+ "MATOMO_ENABLED": "false",
+ "NODE_OPTIONS": nodeOptions,
+ "HTTP_REQUEST_TIMEOUT_MS": "60000" // 60 seconds timeout
+ ]
+
+ inputs.files(fileTree(project.ext.siteStagingDir))
+ inputs.property("Antora version", libs.versions.antora.asProvider().get())
+ outputs.dir(project.ext.siteDir)
}
task buildLocalSite {
- group = 'Site - Local'
- description "Creates a local build of the ref-guide, with local javadocs to link to."
+ group = 'Site - Local'
+ description "Creates a local build of the ref-guide, with local javadocs to link to."
- dependsOn tasks.buildLocalAntoraSite
- dependsOn configurations.localJavadocs
+ dependsOn tasks.buildLocalAntoraSite
+ dependsOn configurations.localJavadocs
- doLast {
- project.logger.lifecycle("The generated local ref-guide can be found at:")
- project.logger.lifecycle("\t${project.ext.siteDir}/index.html")
- }
+ doLast {
+ project.logger.lifecycle("The generated local ref-guide can be found at:")
+ project.logger.lifecycle("\t${project.ext.siteDir}/index.html")
+ }
}
task checkSiteLinks(type: NpxTask) {
- group = 'Verification'
- description "Check that all links in the ref-guide, both internal and java-docs, are correct."
-
- dependsOn tasks.downloadLinkValidator
- dependsOn tasks.buildLocalSite
-
- command = "link-checker"
- args = [
- "${buildDir}/site",
- "--url-ignore", "file:/",
- "--mkdocs",
- "--allow-hash-href",
- "--disable-external",
- "--debug",
- // Ignore the java docs url in the header, since it is an absolute path
- "--url-ignore", "${project(':solr:documentation').docroot.toPath()}/index\\.html",
- "--json",
- "-v",
- ]
-
- def outputFile = "${buildDir}/validation/link-check.json"
- execOverrides {
- // The it variable contains the `ExecSpec`
- it.standardOutput = new TeeOutputStream(it.standardOutput, new FileOutputStream(outputFile))
- }
-
- inputs.files(fileTree(siteDir))
- outputs.file(outputFile)
+ group = 'Verification'
+ description "Check that all links in the ref-guide, both internal and java-docs, are correct."
+
+ dependsOn tasks.downloadLinkValidator
+ dependsOn tasks.buildLocalSite
+
+ command = "link-checker"
+ args = [
+ "${buildDir}/site",
+ "--url-ignore", "file:/",
+ "--mkdocs",
+ "--allow-hash-href",
+ "--disable-external",
+ "--debug",
+ // Ignore the java docs url in the header, since it is an absolute path
+ "--url-ignore", "${project(':solr:documentation').docroot.toPath()}/index\\.html",
+ "--json",
+ "-v",
+ ]
+
+ def outputFile = "${buildDir}/validation/link-check.json"
+ execOverrides {
+ // The it variable contains the `ExecSpec`
+ it.standardOutput = new TeeOutputStream(it.standardOutput, new FileOutputStream(outputFile))
+ }
+
+ inputs.files(fileTree(siteDir))
+ outputs.file(outputFile)
}
/*
Build and setup the official Site
*/
task setOfficialAntoraYaml {
- group = 'Site - Official'
- description "Setups the local antora.yml as the official antora.yml for this branch. Note: This will change the antora.yml in the repo, not a build folder."
+ group = 'Site - Official'
+ description "Setups the local antora.yml as the official antora.yml for this branch. Note: This will change the antora.yml in the repo, not a build folder."
- dependsOn tasks.buildLocalAntoraYaml
+ dependsOn tasks.buildLocalAntoraYaml
- inputs.file(project.ext.localAntoraYaml)
- outputs.file("antora.yml")
+ inputs.file(project.ext.localAntoraYaml)
+ outputs.file("antora.yml")
- doLast {
- copy {
- from project.ext.localAntoraYaml
- into projectDir
- }
+ doLast {
+ copy {
+ from project.ext.localAntoraYaml
+ into projectDir
}
+ }
}
task buildOfficialSite(type: NpxTask) {
- group = 'Site - Official'
- description "Creates a build of the official ref-guide. This will not include local changes."
-
- dependsOn tasks.downloadAntora
- dependsOn configurations.officialPlaybook
+ group = 'Site - Official'
+ description "Creates a build of the official ref-guide. This will not include local changes."
- command = "antora"
-
- def officialPlaybook = "${project.ext.playbooksDir}/${project.ext.officialPlaybook}"
- def extraArgs = []
-
- if (buildLocalUI) {
- dependsOn tasks.buildUIBundle
- extraArgs.addAll([
- "--ui-bundle-url", "${buildDir}/dist/ui-bundle.zip"
- ])
- inputs.files("${buildDir}/dist/ui-bundle.zip")
- }
+ dependsOn tasks.downloadAntora
+ dependsOn configurations.officialPlaybook
- args = [
- officialPlaybook,
- ] + extraArgs
+ command = "antora"
- // Configure HTTP request timeout via preload script to prevent timeout errors
- // when downloading UI bundle from slow networks (especially in CI)
- def nodeOptions = "--require ${projectDir}/increase-request-timeout.js"
+ def officialPlaybook = "${project.ext.playbooksDir}/${project.ext.officialPlaybook}"
+ def extraArgs = []
- environment = [
- "SITE_SEARCH_ENABLED": "true",
- "MATOMO_ENABLED": "true",
- "NODE_OPTIONS": nodeOptions,
- "HTTP_REQUEST_TIMEOUT_MS": "60000" // 60 seconds timeout
- ]
-
- inputs.files(officialPlaybook)
- inputs.property("Antora version", libs.versions.antora.asProvider().get())
- outputs.dir(project.ext.siteDir)
-
- doLast {
- project.logger.lifecycle("The generated official ref-guide can be found at:")
- project.logger.lifecycle("\t${project.ext.siteDir}")
- }
+ if (buildLocalUI) {
+ dependsOn tasks.buildUIBundle
+ extraArgs.addAll([
+ "--ui-bundle-url", "${buildDir}/dist/ui-bundle.zip"
+ ])
+ inputs.files("${buildDir}/dist/ui-bundle.zip")
+ }
+
+ args = [
+ officialPlaybook,
+ ] + extraArgs
+
+ // Configure HTTP request timeout via preload script to prevent timeout errors
+ // when downloading UI bundle from slow networks (especially in CI)
+ def nodeOptions = "--require ${projectDir}/increase-request-timeout.js"
+
+ environment = [
+ "SITE_SEARCH_ENABLED": "true",
+ "MATOMO_ENABLED": "true",
+ "NODE_OPTIONS": nodeOptions,
+ "HTTP_REQUEST_TIMEOUT_MS": "60000" // 60 seconds timeout
+ ]
+
+ inputs.files(officialPlaybook)
+ inputs.property("Antora version", libs.versions.antora.asProvider().get())
+ outputs.dir(project.ext.siteDir)
+
+ doLast {
+ project.logger.lifecycle("The generated official ref-guide can be found at:")
+ project.logger.lifecycle("\t${project.ext.siteDir}")
+ }
}
/*
@@ -535,34 +545,34 @@ task buildOfficialSite(type: NpxTask) {
*/
sourceSets {
- test {
- java {
- srcDirs = ['modules/configuration-guide/examples', 'modules/deployment-guide/examples', 'modules/getting-started/examples', 'modules/indexing-guide/examples', 'modules/query-guide/examples']
- }
+ test {
+ java {
+ srcDirs =
+ ['modules/configuration-guide/examples', 'modules/deployment-guide/examples', 'modules/getting-started/examples', 'modules/indexing-guide/examples', 'modules/query-guide/examples']
}
+ }
}
dependencies {
- // For the SolrJ examples
- testImplementation project(":solr:core")
- testImplementation project(":solr:solrj")
- testImplementation project(":solr:solrj-jetty")
- testRuntimeOnly project(":solr:modules:sql")
- testImplementation project(":solr:test-framework")
- testImplementation libs.junit.junit
- testImplementation libs.apache.lucene.testframework
+ // For the SolrJ examples
+ testImplementation project(":solr:core")
+ testImplementation project(":solr:solrj")
+ testImplementation project(":solr:solrj-jetty")testRuntimeOnly project(":solr:modules:sql")
+ testImplementation project(":solr:test-framework")
+ testImplementation libs.junit.junit
+ testImplementation libs.apache.lucene.testframework
}
// Copy all the test resource files from SolrJ to the build/resources/test directory
// of the examples so we can avoid duplication of the test resource files like
// schemas and SolrConfigs.
tasks.register('copySolrjTestResources', Copy) {
- from(project(':solr:solrj').sourceSets.test.resources.srcDirs) {
- exclude '**/*.java'
- }
- into sourceSets.test.output.resourcesDir
+ from(project(':solr:solrj').sourceSets.test.resources.srcDirs) {
+ exclude '**/*.java'
+ }
+ into sourceSets.test.output.resourcesDir
}
tasks.named('processTestResources').configure {
- dependsOn copySolrjTestResources
+ dependsOn copySolrjTestResources
}
diff --git a/solr/solrj-zookeeper/build.gradle b/solr/solrj-zookeeper/build.gradle
index e04f230b30e..dc975966e3c 100644
--- a/solr/solrj-zookeeper/build.gradle
+++ b/solr/solrj-zookeeper/build.gradle
@@ -20,40 +20,40 @@ apply plugin: 'java-library'
description = 'Solrj-ZooKeeper - SolrJ requiring ZooKeeper'
dependencies {
- // Spotbugs Annotations are only needed for old findbugs
- // annotation usage like in Zookeeper during compilation time.
- // It is not included in the release so exclude from checks.
- compileOnly libs.spotbugs.annotations
- permitUnusedDeclared libs.spotbugs.annotations
- // Exclude these from jar validation and license checks.
- configurations.jarValidation {
- exclude group: "com.github.spotbugs", module: "spotbugs-annotations"
- }
-
- implementation project(':solr:solrj')
- implementation project(':solr:solrj-jetty')
+ // Spotbugs Annotations are only needed for old findbugs
+ // annotation usage like in Zookeeper during compilation time.
+ // It is not included in the release so exclude from checks.
+ compileOnly libs.spotbugs.annotations
+ permitUnusedDeclared libs.spotbugs.annotations
+ // Exclude these from jar validation and license checks.
+ configurations.jarValidation {
+ exclude group: "com.github.spotbugs", module: "spotbugs-annotations"
+ }
+
+ implementation project(':solr:solrj')
+ implementation project(':solr:solrj-jetty')
implementation project(':solr:api')
- implementation libs.slf4j.api
+ implementation libs.slf4j.api
- implementation(libs.apache.curator.client, {
- exclude group: 'org.apache.zookeeper', module: 'zookeeper'
- })
- api(libs.apache.curator.framework, {
- exclude group: 'org.apache.zookeeper', module: 'zookeeper'
- })
- api(libs.apache.zookeeper.zookeeper, {
- exclude group: "org.apache.yetus", module: "audience-annotations"
- })
- implementation(libs.apache.zookeeper.jute) {
- exclude group: 'org.apache.yetus', module: 'audience-annotations'
- }
+ implementation(libs.apache.curator.client, {
+ exclude group: 'org.apache.zookeeper', module: 'zookeeper'
+ })
+ api(libs.apache.curator.framework, {
+ exclude group: 'org.apache.zookeeper', module: 'zookeeper'
+ })
+ api(libs.apache.zookeeper.zookeeper, {
+ exclude group: "org.apache.yetus", module: "audience-annotations"
+ })
+ implementation(libs.apache.zookeeper.jute) {
+ exclude group: 'org.apache.yetus', module: 'audience-annotations'
+ }
- testImplementation project(':solr:test-framework')
- testImplementation project(':solr:core')
+ testImplementation project(':solr:test-framework')
+ testImplementation project(':solr:core')
- testImplementation libs.junit.junit
- testImplementation libs.commonsio.commonsio
+ testImplementation libs.junit.junit
+ testImplementation libs.commonsio.commonsio
- permitTestUsedUndeclared project(':solr:solrj-zookeeper') // duh!
+ permitTestUsedUndeclared project(':solr:solrj-zookeeper') // duh!
}
diff --git a/solr/solrj/build.gradle b/solr/solrj/build.gradle
index f2a9e8b0445..2c554cddfe5 100644
--- a/solr/solrj/build.gradle
+++ b/solr/solrj/build.gradle
@@ -23,7 +23,6 @@ plugins {
import com.diffplug.gradle.spotless.JavaExtension
-
description = 'Solrj - Solr Java Client'
dependencies {
diff --git a/solr/test-framework/build.gradle b/solr/test-framework/build.gradle
index 9a6ca030350..4daeb6dd99e 100644
--- a/solr/test-framework/build.gradle
+++ b/solr/test-framework/build.gradle
@@ -41,7 +41,6 @@ dependencies {
implementation libs.apache.lucene.queries
implementation libs.apache.lucene.suggest
-
var zkExcludes = {
exclude group: "org.apache.yetus", module: "audience-annotations"
}
@@ -60,7 +59,7 @@ dependencies {
implementation(libs.apache.zookeeper.zookeeper, zkExcludes)
implementation(libs.apache.zookeeper.jute, zkExcludes)
- implementation(variantOf(libs.apache.zookeeper.zookeeper) { classifier 'tests' }, zkExcludes)
+ implementation(variantOf(libs.apache.zookeeper.zookeeper) {classifier 'tests'}, zkExcludes)
implementation libs.commonsio.commonsio
implementation libs.slf4j.api
diff --git a/solr/webapp/build.gradle b/solr/webapp/build.gradle
index 3ea3607d021..b07fe5531bf 100644
--- a/solr/webapp/build.gradle
+++ b/solr/webapp/build.gradle
@@ -147,7 +147,7 @@ task finalizeJsBundleDir(type: Sync) {
war {
webAppDirName = "web"
- from (configurations.generatedJSClientBundle, {
+ from(configurations.generatedJSClientBundle, {
into "libs/solr"
})
@@ -155,11 +155,11 @@ war {
// By default, we always build dev that does not optimize generated files for release to reduce build times.
if (gradle.ext.withUiModule) {
if (rootProject.ext.development) {
- from (tasks.generateUiDevFiles) {
+ from(tasks.generateUiDevFiles) {
into "ui"
}
} else {
- from (tasks.generateUiProdFiles) {
+ from(tasks.generateUiProdFiles) {
into "ui"
}
}