Skip to content

Commit d61742d

Browse files
committed
chore: Cleanups and better use of the Gradle API
1 parent e3b289f commit d61742d

File tree

9 files changed

+137
-124
lines changed

9 files changed

+137
-124
lines changed

buildSrc/build.gradle.kts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,6 @@ tasks.compileKotlin {
5858
dependsOn(":call-site-instrumentation-plugin:build")
5959
}
6060

61-
// Allows to transition progressively groovy code to kotlin
62-
tasks.compileGroovy.configure {
63-
dependsOn(tasks.compileKotlin)
64-
classpath += files(tasks.compileKotlin.get().destinationDirectory)
65-
}
66-
6761
testing {
6862
@Suppress("UnstableApiUsage")
6963
suites {

buildSrc/src/main/kotlin/datadog/gradle/plugin/muzzle/MuzzleDirective.kt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,17 @@ open class MuzzleDirective {
2020
var versions: String? = null
2121
var skipVersions: MutableSet<String> = HashSet()
2222
var additionalDependencies: MutableList<String> = ArrayList()
23-
var additionalRepositories: MutableList<RemoteRepository> = ArrayList()
24-
var excludedDependencies: MutableList<String> = ArrayList()
23+
internal var additionalRepositories: MutableList<RemoteRepository> = ArrayList()
24+
internal var excludedDependencies: MutableList<String> = ArrayList()
2525
var assertPass: Boolean = false
2626
var assertInverse: Boolean = false
2727
var skipFromReport: Boolean = false
28-
var coreJdk: Boolean = false
28+
internal var isCoreJdk: Boolean = false
2929
var includeSnapshots: Boolean = false
3030
var javaVersion: String? = null
3131

3232
fun coreJdk(version: String? = null) {
33-
coreJdk = true
33+
isCoreJdk = true
3434
javaVersion = version
3535
}
3636

@@ -90,7 +90,7 @@ open class MuzzleDirective {
9090
}
9191

9292
override fun toString(): String {
93-
return if (coreJdk) {
93+
return if (isCoreJdk) {
9494
"${if (assertPass) "Pass" else "Fail"}-core-jdk"
9595
} else {
9696
"${if (assertPass) "pass" else "fail"} $group:$module:$versions"

buildSrc/src/main/kotlin/datadog/gradle/plugin/muzzle/MuzzleMavenRepoUtils.kt

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import org.eclipse.aether.version.Version
1717
import org.gradle.api.GradleException
1818
import java.nio.file.Files
1919

20-
object MuzzleMavenRepoUtils {
20+
internal object MuzzleMavenRepoUtils {
2121
/**
2222
* Remote repositories used to query version ranges and fetch dependencies
2323
*/
@@ -63,7 +63,6 @@ object MuzzleMavenRepoUtils {
6363
/**
6464
* Create a list of muzzle directives which assert the opposite of the given MuzzleDirective.
6565
*/
66-
@JvmStatic
6766
fun inverseOf(
6867
muzzleDirective: MuzzleDirective,
6968
system: RepositorySystem,
@@ -117,7 +116,6 @@ object MuzzleMavenRepoUtils {
117116
* Resolves the version range for a given MuzzleDirective using the provided RepositorySystem and RepositorySystemSession.
118117
* Equivalent to the Groovy implementation in MuzzlePlugin.
119118
*/
120-
@JvmStatic
121119
fun resolveVersionRange(
122120
muzzleDirective: MuzzleDirective,
123121
system: RepositorySystem,
@@ -137,7 +135,20 @@ object MuzzleMavenRepoUtils {
137135
return system.resolveVersionRange(session, rangeRequest)
138136
}
139137

140-
@JvmStatic
138+
/**
139+
* Resolves instrumentation names and their corresponding artifact versions for a given directive.
140+
*
141+
* Loads the `MuzzleVersionScanPlugin` class using the provided `ClassLoader`, invokes its
142+
* `listInstrumentationNames` method to get all instrumentation names for the directive, and
143+
* constructs a map of `TestedArtifact` objects keyed by their unique identifier. For each
144+
* instrumentation name, the lowest and highest versions are determined and stored.
145+
*
146+
* @param directive the `MuzzleDirective` containing group, module, and name information
147+
* @param cl the `ClassLoader` used to load the scan plugin class
148+
* @param lowVersion the lowest version to consider
149+
* @param highVersion the highest version to consider
150+
* @return a map of instrumentation name keys to their corresponding `TestedArtifact` objects
151+
*/
141152
fun resolveInstrumentationAndJarVersions(
142153
directive: MuzzleDirective,
143154
cl: ClassLoader,
@@ -148,6 +159,7 @@ object MuzzleMavenRepoUtils {
148159
val listMethod = scanPluginClass.getMethod("listInstrumentationNames", ClassLoader::class.java, String::class.java)
149160
@Suppress("UNCHECKED_CAST")
150161
val names = listMethod.invoke(null, cl, directive.name) as Set<String>
162+
151163
val ret = mutableMapOf<String, TestedArtifact>()
152164
for (n in names) {
153165
val testedArtifact = TestedArtifact(n, directive.group ?: "", directive.module ?: "", lowVersion, highVersion)
@@ -166,20 +178,17 @@ object MuzzleMavenRepoUtils {
166178
/**
167179
* Returns the highest of two Version objects.
168180
*/
169-
@JvmStatic
170181
fun highest(a: Version, b: Version): Version = if (a.compareTo(b) > 0) a else b
171182

172183
/**
173184
* Returns the lowest of two Version objects.
174185
*/
175-
@JvmStatic
176186
fun lowest(a: Version, b: Version): Version = if (a.compareTo(b) < 0) a else b
177187

178188
/**
179189
* Convert a muzzle directive to a set of artifacts for all filtered versions.
180190
* Throws GradleException if no artifacts are found.
181191
*/
182-
@JvmStatic
183192
fun muzzleDirectiveToArtifacts(
184193
muzzleDirective: MuzzleDirective,
185194
rangeResult: VersionRangeResult

buildSrc/src/main/kotlin/datadog/gradle/plugin/muzzle/MuzzlePlugin.kt

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ class MuzzlePlugin : Plugin<Project> {
5757
// compileMuzzle compiles all projects required to run muzzle validation.
5858
// Not adding group and description to keep this task from showing in `gradle tasks`.
5959
val compileMuzzle = project.tasks.register("compileMuzzle") {
60-
// dependsOn(project.tasks.withType(InstrumentTask::class))
61-
dependsOn(project.tasks.withType(Class.forName("InstrumentTask") as Class<Task>)) // TODO
60+
dependsOn(project.tasks.withType(Class.forName("InstrumentTask") as Class<Task>)) // kotlin can't see groovy code
6261
dependsOn(bootstrapProject.tasks.named("compileJava"))
6362
dependsOn(bootstrapProject.tasks.named("compileMain_java11Java"))
6463
dependsOn(toolingProject.tasks.named("compileJava"))
@@ -67,7 +66,7 @@ class MuzzlePlugin : Plugin<Project> {
6766
val muzzleTask = project.tasks.register<MuzzleTask>("muzzle") {
6867
description = "Run instrumentation muzzle on compile time dependencies"
6968
doLast {
70-
if (!project.extensions.getByType(MuzzleExtension::class.java).directives.any { it.assertPass }) {
69+
if (!project.extensions.getByType<MuzzleExtension>().directives.any { it.assertPass }) {
7170
project.logger.info("No muzzle pass directives configured. Asserting pass against instrumentation compile-time dependencies")
7271
assertMuzzle(muzzleBootstrap, muzzleTooling, project)
7372
}
@@ -117,12 +116,12 @@ class MuzzlePlugin : Plugin<Project> {
117116
project.afterEvaluate {
118117
// use runAfter to set up task finalizers in version order
119118
var runAfter: TaskProvider<MuzzleTask> = muzzleTask
120-
121-
project.extensions.getByType<MuzzleExtension>().directives.forEach { muzzleDirective ->
122-
project.logger.debug("configuring $muzzleDirective")
123119

124-
if (muzzleDirective.coreJdk) {
125-
runAfter = addMuzzleTask(muzzleDirective, null, project, runAfter, muzzleBootstrap, muzzleTooling)
120+
project.extensions.getByType<MuzzleExtension>().directives.forEach { directive ->
121+
project.logger.debug("configuring $directive")
122+
123+
if (directive.isCoreJdk) {
124+
runAfter = addMuzzleTask(directive, null, project, runAfter, muzzleBootstrap, muzzleTooling)
126125
} else {
127126
val range = resolveVersionRange(directive, system, session)
128127

@@ -134,8 +133,8 @@ class MuzzlePlugin : Plugin<Project> {
134133
inverseOf(directive, system, session).forEach { inverseDirective ->
135134
val inverseRange = resolveVersionRange(inverseDirective, system, session)
136135

137-
muzzleDirectiveToArtifacts(inverseDirective, inverseRange).forEach { singleVersion ->
138-
runAfter = addMuzzleTask(inverseDirective, singleVersion, project, runAfter, muzzleBootstrap, muzzleTooling)
136+
muzzleDirectiveToArtifacts(inverseDirective, inverseRange).forEach {
137+
runAfter = addMuzzleTask(inverseDirective, it, project, runAfter, muzzleBootstrap, muzzleTooling)
139138
}
140139
}
141140
}
@@ -179,19 +178,23 @@ class MuzzlePlugin : Plugin<Project> {
179178
muzzleBootstrap: NamedDomainObjectProvider<Configuration>,
180179
muzzleTooling: NamedDomainObjectProvider<Configuration>
181180
): TaskProvider<MuzzleTask> {
182-
val muzzleTaskName = if (muzzleDirective.coreJdk) {
181+
val muzzleTaskName = if (muzzleDirective.isCoreJdk) {
183182
"muzzle-Assert$muzzleDirective"
184183
} else {
185184
"muzzle-Assert${if (muzzleDirective.assertPass) "Pass" else "Fail"}-${versionArtifact?.groupId}-${versionArtifact?.artifactId}-${versionArtifact?.version}${if (muzzleDirective.name != null) "-${muzzleDirective.name}" else ""}"
186185
}
187186
instrumentationProject.configurations.register(muzzleTaskName) {
188-
if (!muzzleDirective.coreJdk) {
189-
var depId = "${versionArtifact?.groupId}:${versionArtifact?.artifactId}:${versionArtifact?.version}"
190-
if (versionArtifact?.classifier != null) {
191-
depId += ":${versionArtifact.classifier}"
187+
if (!muzzleDirective.isCoreJdk && versionArtifact != null) {
188+
var depId = buildString {
189+
append("${versionArtifact.groupId}:${versionArtifact.artifactId}:${versionArtifact.version}")
190+
191+
versionArtifact.classifier?.let {
192+
append(":")
193+
append(it)
194+
}
192195
}
193196

194-
val dep: Dependency = instrumentationProject.dependencies.create(depId) {
197+
val dep = instrumentationProject.dependencies.create(depId) {
195198
isTransitive = true
196199

197200
// The following optional transitive dependencies are brought in by some legacy module such as log4j 1.x but are no

buildSrc/src/main/kotlin/datadog/gradle/plugin/muzzle/MuzzlePluginUtils.kt

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,6 @@ import org.gradle.api.tasks.SourceSet
66
import org.gradle.api.tasks.SourceSetContainer
77
import org.gradle.kotlin.dsl.getByType
88

9-
internal fun createAgentClassPath(project: Project): FileCollection {
10-
project.logger.info("Creating agent classpath for $project")
11-
val cp = project.files()
12-
cp.from(project.allMainSourceSet.map { it.runtimeClasspath })
13-
14-
if (project.logger.isInfoEnabled) {
15-
cp.forEach { project.logger.info("-- $it") }
16-
}
17-
return cp
18-
}
19-
20-
internal fun createMuzzleClassPath(project: Project, muzzleTaskName: String): FileCollection {
21-
project.logger.info("Creating muzzle classpath for $muzzleTaskName")
22-
val cp = project.files()
23-
val config = if (muzzleTaskName == "muzzle") {
24-
project.configurations.named("compileClasspath").get()
25-
} else {
26-
project.configurations.named(muzzleTaskName).get()
27-
}
28-
cp.from(config)
29-
if (project.logger.isInfoEnabled) {
30-
cp.forEach { project.logger.info("-- $it") }
31-
}
32-
return cp
33-
}
34-
359
internal val Project.mainSourceSet: SourceSet
3610
get() = project.extensions.getByType<SourceSetContainer>().named(SourceSet.MAIN_SOURCE_SET_NAME).get()
3711

buildSrc/src/main/kotlin/datadog/gradle/plugin/muzzle/MuzzleReportUtils.kt

Lines changed: 52 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -7,44 +7,48 @@ import org.eclipse.aether.RepositorySystem
77
import org.eclipse.aether.RepositorySystemSession
88
import org.eclipse.aether.util.version.GenericVersionScheme
99
import org.gradle.api.Project
10-
import org.gradle.kotlin.dsl.findByType
11-
import java.io.File
10+
import org.gradle.kotlin.dsl.getByType
1211
import java.net.URLClassLoader
1312
import java.util.SortedMap
1413
import java.util.TreeMap
1514
import java.util.function.BiFunction
1615

17-
object MuzzleReportUtils {
18-
@JvmStatic
16+
internal object MuzzleReportUtils {
17+
private const val MUZZLE_DEPS_RESULTS = "muzzle-deps-results"
18+
private const val MUZZLE_TEST_RESULTS = "muzzle-test-results"
19+
1920
fun dumpVersionRanges(project: Project) {
2021
val system: RepositorySystem = MuzzleMavenRepoUtils.newRepositorySystem()
2122
val session: RepositorySystemSession = MuzzleMavenRepoUtils.newRepositorySystemSession(system)
2223
val versions = TreeMap<String, TestedArtifact>()
23-
val directives = project.extensions.findByType<MuzzleExtension>()?.directives ?: emptyList()
24-
directives.filter { !it.coreJdk && !it.skipFromReport }.forEach { directive ->
25-
val range = MuzzleMavenRepoUtils.resolveVersionRange(directive, system, session)
26-
val cp = project.files(project.mainSourceSet.runtimeClasspath).map { it.toURI().toURL() }.toTypedArray()
27-
val cl = URLClassLoader(cp, null)
28-
val partials = resolveInstrumentationAndJarVersions(directive, cl, range.lowestVersion, range.highestVersion)
29-
partials.forEach { (key, value) ->
30-
versions.merge(key, value, BiFunction { x, y ->
31-
TestedArtifact(
32-
x.instrumentation, x.group, x.module,
33-
lowest(x.lowVersion, y.lowVersion),
34-
highest(x.highVersion, y.highVersion)
35-
)
36-
})
24+
25+
project.extensions.getByType<MuzzleExtension>().directives
26+
.filter { !it.isCoreJdk && !it.skipFromReport }
27+
.forEach { directive ->
28+
val range = MuzzleMavenRepoUtils.resolveVersionRange(directive, system, session)
29+
val cp = project.files(project.mainSourceSet.runtimeClasspath).map { it.toURI().toURL() }.toTypedArray()
30+
val cl = URLClassLoader(cp, null)
31+
val partials = resolveInstrumentationAndJarVersions(directive, cl, range.lowestVersion, range.highestVersion)
32+
33+
partials.forEach { (key, value) ->
34+
versions.merge(key, value, BiFunction { x, y ->
35+
TestedArtifact(
36+
x.instrumentation, x.group, x.module,
37+
lowest(x.lowVersion, y.lowVersion),
38+
highest(x.highVersion, y.highVersion)
39+
)
40+
})
41+
}
3742
}
38-
}
3943
dumpVersionsToCsv(project, versions)
4044
}
4145

4246
private fun dumpVersionsToCsv(project: Project, versions: SortedMap<String, TestedArtifact>) {
43-
val filename = project.path.replaceFirst("^:", "").replace(":", "_")
44-
val dir = project.rootProject.layout.buildDirectory.dir("muzzle-deps-results").get().asFile.apply {
45-
mkdirs()
46-
}
47-
with(File(dir, "$filename.csv")) {
47+
val filename = project.path.replaceFirst("^:".toRegex(), "").replace(":", "_")
48+
49+
val verrsionsFile = project.rootProject.layout.buildDirectory.file("$MUZZLE_DEPS_RESULTS/$filename.csv")
50+
with(project.file(verrsionsFile)) {
51+
parentFile.mkdirs()
4852
writeText("instrumentation,jarGroupId,jarArtifactId,lowestVersion,highestVersion\n")
4953
versions.values.forEach {
5054
appendText(
@@ -64,13 +68,17 @@ object MuzzleReportUtils {
6468
/**
6569
* Merges all muzzle report CSVs in the build directory into a single map and writes the merged results to a CSV.
6670
*/
67-
@JvmStatic
6871
fun mergeReports(project: Project) {
69-
val dir = File(project.rootProject.buildDir, "muzzle-deps-results")
72+
val versionReports = project.fileTree(project.rootProject.layout.buildDirectory.dir(MUZZLE_DEPS_RESULTS)) {
73+
include("*.csv")
74+
}
75+
7076
val map = TreeMap<String, TestedArtifact>()
7177
val versionScheme = GenericVersionScheme()
72-
dir.listFiles { file -> file.name.endsWith(".csv") }?.forEach { file ->
73-
file.useLines { lines ->
78+
79+
versionReports.forEach {
80+
project.logger.info("Processing muzzle report: $it")
81+
it.useLines { lines ->
7482
lines.forEachIndexed { idx, line ->
7583
if (idx == 0) return@forEachIndexed // skip header
7684
val split = line.split(",")
@@ -100,22 +108,25 @@ object MuzzleReportUtils {
100108
/**
101109
* Generates a JUnit-style XML report for muzzle results.
102110
*/
103-
@JvmStatic
104111
fun generateResultsXML(project: Project, millis: Long) {
105112
val seconds = millis.toDouble() / 1000.0
106113
val name = "${project.path}:muzzle"
107-
val dirname = name.replaceFirst("^:", "").replace(":", "_")
108-
val dir = File(project.rootProject.buildDir, "muzzle-test-results/$dirname")
109-
dir.mkdirs()
110-
val file = File(dir, "results.xml")
111-
file.writeText(
112-
"""
113-
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
114-
"<testsuite name=\"$name\" tests=\"1\" id=\"0\" time=\"$seconds\">\n" +
115-
" <testcase name=\"$name\" time=\"$seconds\">\n" +
116-
" </testcase>\n" +
117-
"</testsuite>\n"
114+
val dirname = name.replaceFirst("^:".toRegex(), "").replace(":", "_")
115+
116+
val dir = project.rootProject.layout.buildDirectory.dir("$MUZZLE_TEST_RESULTS/$dirname/results.xml")
117+
118+
with(project.file(dir)) {
119+
parentFile.mkdirs()
120+
writeText(
121+
"""
122+
<?xml version="1.0" encoding="UTF-8"?>
123+
<testsuite name="$name" tests="1" id="0" time="$seconds">
124+
<testcase name="$name" time="$seconds">
125+
</testcase>
126+
</testsuite>
118127
""".trimIndent()
119-
)
128+
)
129+
project.logger.info("Wrote muzzle results report to\n $this")
130+
}
120131
}
121132
}

0 commit comments

Comments
 (0)