Skip to content

Gradle modernization #1642

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Mar 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .evergreen/.evg.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1875,15 +1875,15 @@ axes:
- id: "2.11"
display_name: "Scala 2.11"
variables:
SCALA: "2.11.12"
SCALA: "2.11"
- id: "2.12"
display_name: "Scala 2.12"
variables:
SCALA: "2.12.20"
SCALA: "2.12"
- id: "2.13"
display_name: "Scala 2.13"
variables:
SCALA: "2.13.15"
SCALA: "2.13"

# Choice of MongoDB storage engine
- id: storage-engine
Expand Down
4 changes: 2 additions & 2 deletions .evergreen/publish.sh
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ SYSTEM_PROPERTIES="-Dorg.gradle.internal.publish.checksums.insecure=true -Dorg.g

./gradlew -version
./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info ${TASK} # Scala 2.13 is published as result of this gradle execution.
./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PdefaultScalaVersions=2.12.12
./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PdefaultScalaVersions=2.11.12
./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PscalaVersion=2.12
./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PscalaVersion=2.11
4 changes: 2 additions & 2 deletions .github/workflows/bump-version.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ fi
FROM_VERSION=$1
TO_VERSION=$2

sed --in-place "s/version = '${FROM_VERSION}'/version = '${TO_VERSION}'/g" build.gradle
git commit -m "Version: bump ${TO_VERSION}" build.gradle
sed --in-place "s/version=${FROM_VERSION}/version=${TO_VERSION}/g" gradle.properties
git commit -m "Version: bump ${TO_VERSION}" gradle.properties
136 changes: 133 additions & 3 deletions bom/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
group = "org.mongodb"
description = "This Bill of Materials POM simplifies dependency management when referencing multiple" +
" MongoDB Java Driver artifacts in projects using Gradle or Maven."
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import ProjectExtensions.configureMavenPublication
import groovy.util.Node
import groovy.util.NodeList

plugins {
id("java-platform")
id("project.base")
id("conventions.publishing")
id("conventions.spotless")
}

base.archivesName.set("mongodb-driver-bom")

dependencies {
constraints {
Expand All @@ -21,3 +45,109 @@ dependencies {
api(project(":driver-scala"))
}
}

/*
* Handle the multiple versions of Scala we support as defined in `gradle.properties`
*/
val defaultScalaVersion: String = project.findProperty("defaultScalaVersion")!!.toString()
val scalaVersions: List<String>? = project.findProperty("supportedScalaVersions")?.toString()?.split(",")

assert(!scalaVersions.isNullOrEmpty()) {
"Scala versions must be provided as a comma-separated list in the 'supportedScalaVersions' project property"
}

/*
* Apply the Java Platform plugin to create the BOM
* Modify the generated POM to include all supported versions of Scala for driver-scala or bson-scala.
*/
configureMavenPublication {
components.findByName("javaPlatform")?.let { from(it) }

pom {
name.set("bom")
description.set(
"This Bill of Materials POM simplifies dependency management when referencing multiple MongoDB Java Driver artifacts in projects using Gradle or Maven.")

withXml {
val pomXml: Node = asNode()

val dependencyManagementNode = pomXml.getNode("dependencyManagement")
assert(dependencyManagementNode != null) {
"<dependencyManagement> node not found in the generated BOM POM"
}
val dependenciesNode = dependencyManagementNode.getNode("dependencies")
assert(dependenciesNode != null) { "<dependencies> node not found in the generated BOM POM" }

val existingScalaDeps =
dependenciesNode!!
.children()
.map { it as Node }
.filter { it.getNode("artifactId")?.text()?.contains("scala") ?: false }

existingScalaDeps.forEach {
val groupId: String = it.getNode("groupId")!!.text()
val originalArtifactId: String = it.getNode("artifactId")!!.text()
val artifactVersion: String = it.getNode("version")!!.text()

// Add multiple versions with Scala suffixes for each Scala-related dependency.
scalaVersions!!.forEach { scalaVersion ->
if (scalaVersion != defaultScalaVersion) {
// Replace scala version suffix
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

super minor. scala version -> Scala version? Don't wanna make a fuss about it. Feel free to ignore.

val newArtifactId: String = originalArtifactId.replace(defaultScalaVersion, scalaVersion)
val dependencyNode = dependenciesNode.appendNode("dependency")
dependencyNode.appendNode("groupId", groupId)
dependencyNode.appendNode("artifactId", newArtifactId)
dependencyNode.appendNode("version", artifactVersion)
}
}
}
}
}
}

/*
* Validate the BOM file.
*/
tasks.withType<GenerateMavenPom> {
doLast {
pom.withXml {
val pomXml: Node = asNode()
Comment on lines +113 to +114
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like the validation isn’t currently being executed, becausepom.withXml {} runs during the configuration phase (before the POM file is written), placing it inside a doLast block causes it to be skipped.

One alternative is to remove pom.WithXml block and parse the generated POM file directly using XmlParser, as we did previously:
val pomXml: Node = XmlParser().parse(destination)

The rest of the logic should not be affected after the change.

val dependenciesNode = pomXml.getNode("dependencyManagement").getNode("dependencies")
assert(dependenciesNode!!.children().isNotEmpty()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These assertions only take effect when the JVM is run with the -ea flag, which could lead to silent failures. We could replace assert() with require() to ensure the validation always runs.

"BOM must contain more then one <dependency> element:\n$destination"
}

dependenciesNode
.children()
.map { it as Node }
.forEach {
val groupId: String = it.getNode("groupId")!!.text()
assert(groupId.startsWith("org.mongodb")) {
"BOM must contain only 'org.mongodb' dependencies, but found '$groupId':\n$destination"
}

/*
* The <scope> and <optional> tags should be omitted in BOM dependencies.
* This ensures that consuming projects have the flexibility to decide whether a dependency is optional in their context.
*
* The BOM's role is to provide version information, not to dictate inclusion or exclusion of dependencies.
*/
assert(it.getNode("scope") == null) {
"BOM must not contain <scope> elements in dependency:\n$destination"
}
assert(it.getNode("optional") == null) {
"BOM must not contain <optional> elements in dependency:\n$destination"
}
}
}
}
}

/** A node lookup helper. */
private fun Node?.getNode(nodeName: String): Node? {
val found = this?.get(nodeName)
if (found is NodeList && found.isNotEmpty()) {
return found[0] as Node
}
return null
}
126 changes: 10 additions & 116 deletions bson-kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -13,133 +13,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import io.gitlab.arturbosch.detekt.Detekt
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import ProjectExtensions.configureJarManifest
import ProjectExtensions.configureMavenPublication

plugins {
id("org.jetbrains.kotlin.jvm")
id("java-library")

// Test based plugins
alias(libs.plugins.spotless)
alias(libs.plugins.dokka)
alias(libs.plugins.detekt)
}

repositories {
mavenCentral()
google()
}
plugins { id("project.kotlin") }

base.archivesName.set("bson-kotlin")

description = "Bson Kotlin Codecs"

ext.set("pomName", "Bson Kotlin")

dependencies {
// Align versions of all Kotlin components
implementation(platform(libs.kotlin.bom))
implementation(libs.kotlin.stdlib.jdk8)

api(project(path = ":bson", configuration = "default"))
implementation(libs.kotlin.reflect)

testImplementation(libs.junit.kotlin)
// Test case checks MongoClientSettings.getDefaultCodecRegistry() support
testImplementation(project(path = ":driver-core", configuration = "default"))
}

kotlin { explicitApi() }

tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "1.8" }

// ===========================
// Code Quality checks
// ===========================
spotless {
kotlinGradle {
ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) }
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)")
}

kotlin {
target("**/*.kt")
ktfmt().dropboxStyle().configure { it.setMaxWidth(120) }
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
licenseHeaderFile(rootProject.file("config/mongodb.license"))
}

format("extraneous") {
target("*.xml", "*.yml", "*.md")
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
configureMavenPublication {
pom {
name.set("BSON Kotlin")
description.set("The BSON Codec for Kotlin")
url.set("https://bsonspec.org")
}
}

tasks.named("check") { dependsOn("spotlessApply") }

detekt {
allRules = true // fail build on any finding
buildUponDefaultConfig = true // preconfigure defaults
config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run,
// overwriting default behavior
baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt
source =
files(
file("src/main/kotlin"),
file("src/test/kotlin"),
file("src/integrationTest/kotlin"),
)
}

tasks.withType<Detekt>().configureEach {
reports {
html.required.set(true) // observe findings in your browser with structure and code snippets
xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins
txt.required.set(false) // similar to the console output, contains issue signature to manually edit
}
}

spotbugs { showProgress.set(true) }

// ===========================
// Test Configuration
// ===========================

tasks.test { useJUnitPlatform() }

// ===========================
// Dokka Configuration
// ===========================
val dokkaOutputDir = "${rootProject.buildDir}/docs/${base.archivesName.get()}"

tasks.dokkaHtml.configure {
outputDirectory.set(file(dokkaOutputDir))
moduleName.set(base.archivesName.get())
}

val cleanDokka by tasks.register<Delete>("cleanDokka") { delete(dokkaOutputDir) }

project.parent?.tasks?.named("docs") {
dependsOn(tasks.dokkaHtml)
mustRunAfter(cleanDokka)
}

tasks.javadocJar.configure {
dependsOn(cleanDokka, tasks.dokkaHtml)
archiveClassifier.set("javadoc")
from(dokkaOutputDir)
}

// ===========================
// Sources publishing configuration
// ===========================
tasks.sourcesJar { from(project.sourceSets.main.map { it.kotlin }) }

afterEvaluate { tasks.jar { manifest { attributes["Automatic-Module-Name"] = "org.mongodb.bson.kotlin" } } }
configureJarManifest { attributes["Automatic-Module-Name"] = "org.mongodb.bson.kotlin" }
Loading