Repository navigation
Expand file tree
/
Copy pathbuild.gradle
More file actions
652 lines (588 loc) · 27.6 KB
/
Copy pathbuild.gradle
File metadata and controls
652 lines (588 loc) · 27.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
* Copyright and related rights waived via CC0
*
* You should have received a copy of the CC0 legalcode along with this
* work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
import groovy.json.JsonSlurper
import org.graalvm.internal.tck.utils.CoordinateUtils
import org.graalvm.internal.tck.utils.NativeImageConfigUtils
import org.graalvm.internal.tck.utils.TestInfraLoggingUtils
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
plugins {
id 'base'
id "com.diffplug.spotless" version "6.3.0"
id "org.graalvm.internal.tck-base"
}
allprojects {
repositories {
mavenCentral()
maven {
name = "Confluent"
url = uri("https://packages.confluent.io/maven/")
}
mavenLocal()
}
}
// NOTE: this version serves only as a placeholder and will be overridden by the CI when creating a new release
project.version("1.0.0-SNAPSHOT")
// gradle check
spotless {
json {
target(
tck.metadataRoot.map { it.toString() + '/**/*.json' }.get(),
tck.testRoot.map { it.toString() + '/**/*.json' }.get(),
tck.repoRoot.map { it.toString() + '/real-use-tests/src/**/*.json' }.get(),
tck.repoRoot.map { it.toString() + '/stats/**/*.json' }.get()
)
targetExclude(
tck.testRoot.map { it.toString() + '/**/build/**/*.json' }.get(),
tck.repoRoot.map { it.toString() + '/real-use-tests/src/**/build/**/*.json' }.get(),
tck.repoRoot.map { it.toString() + '/.github/**/*.json' }.get()
)
gson()
.indentWithSpaces(2)
.sortByKeys()
.version("2.9.0")
}
String[] noHeaderDirs = [
'native-build-tools/**', // external repository
'docs/**', // only .md files
'metadata/**', // only .json files
'**/build/**', // not relevant
'**/.gradle/**', // not relevant
'forge/local_repositories/**', // third-party sources Forge downloads, not ours to format
'gradle/wrapper/**', // not relevant
'tests/src/**/generated/**/*.java',
'gradle/header.java',
'gradle/header.sh',
]
java {
target('**/*.java')
targetExclude(*noHeaderDirs);
// Place header before package/import/module
licenseHeaderFile("$rootDir/gradle/header.java", "package |import |module ")
}
groovy {
target('**/*.groovy')
targetExclude(*noHeaderDirs)
// Place header before package/import
licenseHeaderFile("$rootDir/gradle/header.java", "package |import ")
}
groovyGradle {
// Build scripts (*.gradle)
target('**/*.gradle')
targetExclude(*noHeaderDirs)
// Insert header at file start (works for any Gradle script layout)
licenseHeaderFile("$rootDir/gradle/header.java", "(?m)^(import\\b|plugins\\b|buildscript\\b|apply\\b|rootProject\\b|pluginManagement\\b|dependencyResolutionManagement\\b)")
}
format('shell') {
target('**/*.sh')
targetExclude(*noHeaderDirs)
// Ensure header appears after shebang if present, else at the very top.
def shHeader = file("$rootDir/gradle/header.sh").text
// If file starts with a shebang and is missing the header, insert it after the shebang
replaceRegex('insert-license-after-shebang',
'(?s)\\A(#![^\\n]*\\n)(?:[ \\t]*\\n)*(?!# Copyright and related rights waived via CC0\\n)',
'$1' + shHeader + "\n")
// If file has no shebang and is missing the header, insert it at the start
replaceRegex('insert-license-at-start',
'(?s)\\A(?!#!)(?!# Copyright and related rights waived via CC0\\n)',
shHeader + "\n")
}
format('python') {
target('**/*.py')
targetExclude(*noHeaderDirs, '**/.venv/**', 'forge/local_repositories/**')
// Ensure header appears after shebang if present, else at the very top.
def pyHeader = file("$rootDir/gradle/header.sh").text
replaceRegex('insert-license-after-shebang',
'(?s)\\A(#![^\\n]*\\n)(?:[ \\t]*\\n)*(?!# Copyright and related rights waived via CC0\\n)',
'$1' + pyHeader + "\n")
replaceRegex('insert-license-at-start',
'(?s)\\A(?!#!)(?!# Copyright and related rights waived via CC0\\n)',
pyHeader + "\n")
}
}
// gradle package §AR-test-harness.8
tasks.register('package', Zip) { task ->
String outputFileName = "graalvm-reachability-metadata-${project.version}.zip"
task.setDescription("Packages current repository to 'build/${outputFileName}'")
task.setGroup(PublishingPlugin.PUBLISH_TASK_GROUP)
task.archiveFileName = outputFileName
task.destinationDirectory = layout.buildDirectory
from(tck.metadataRoot)
}
tasks.register('test') { t ->
t.setDescription("Aggregates tests configured by the TCK harness")
t.setGroup("verification")
}
// Apply the harness after creating the 'test' aggregator to avoid missing property,
// and without applying the 'java' plugin to avoid task name conflicts.
// Harness layer of the two-layer build. §AR-build-infrastructure §AR-test-harness
// The harness the repository must provide: §FS-repository-functional-spec.4.2
apply plugin: "org.graalvm.internal.tck-harness"
tasks.named("check").configure {
dependsOn("validateLibraryStats")
dependsOn("checkDocLinks")
}
static List<Map> testInfraCommands(String gradleCmd, String target) {
def taskNames = [
"validateIndexFiles",
"checkstyle",
"spotlessCheck",
"checkMetadataFiles",
"fetchExistingLibrariesWithNewerVersions",
"test",
"jacocoTestReport",
"listLibraryJars",
"generateDynamicAccessReport",
"generateDynamicAccessCoverageReport",
"generateLibraryStats",
"listTopCoordinatesByMetric",
"generateTopCoordinatesByMetricMatrix",
"listCoordinates",
"generateDependencyGraph",
"splitTestOnlyMetadata"
]
return taskNames.collect { name ->
[name: name, args: [gradleCmd, name, "-Pcoordinates=${target}"]]
}
}
List<String> resolveConcreteCoordinates(String coordinateFilter) {
List<String> matchingCoordinates
if (CoordinateUtils.isFractionalBatch(coordinateFilter)) {
int[] fraction = CoordinateUtils.parseFraction(coordinateFilter)
List<String> allCoordinates = tck.getMatchingCoordinatesStrict("all")
matchingCoordinates = CoordinateUtils.computeBatchedCoordinates(allCoordinates, fraction[0], fraction[1])
} else {
matchingCoordinates = tck.getMatchingCoordinates(coordinateFilter)
}
return matchingCoordinates.findAll { !it.startsWith("samples:") }
}
String resolveSelectedNativeImageMode() {
return NativeImageConfigUtils.resolveSelectedMode(
System.getenv("GVM_TCK_NATIVE_IMAGE_MODE"),
project.findProperty("tck.nativeImageMode")?.toString()
)
}
void printTestInfraReproducer(String gradleCmd, String coordinate, int parallelism) {
String nativeImageMode = resolveSelectedNativeImageMode()
TestInfraLoggingUtils.batchReproducerLines(
"testInfra",
gradleCmd,
nativeImageMode,
coordinate,
parallelism
).each { println(it) }
}
// Infrastructure end-to-end test for a single coordinate: §AR-test-harness.
tasks.register('testInfra') { t ->
t.group = "verification"
t.setDescription("""Runs clean and pullAllowedDockerImages, then runs (${testInfraCommands('', '').collect { it.name }.join(', ')}) concurrently with isolated logs for a single coordinate.
Options: -Pcoordinate or -Pcoordinates to specify the target; -Pparallelism to control the number of concurrent tasks.""")
doLast {
def coordinateProp = ((project.findProperty('coordinate') ?: project.findProperty('coordinates')) ?: '').toString().trim()
if (coordinateProp.isEmpty()) {
throw new GradleException("Missing -Pcoordinate=<group:artifact:version|k/n|all> (or -Pcoordinates).")
}
def gradleCmd = System.getProperty("os.name").toLowerCase().contains("windows") ? "gradlew.bat" : "./gradlew"
int parallelism = parsePositiveIntProp('parallelism', 4)
println("Using parallelism=${parallelism} for testInfra.")
List<String> concreteCoordinates = resolveConcreteCoordinates(coordinateProp)
if (concreteCoordinates.isEmpty()) {
throw new GradleException("No matching coordinates found for '${coordinateProp}'.")
}
concreteCoordinates.each { coordinate ->
printTestInfraReproducer(gradleCmd, coordinate, parallelism)
}
def logsDir = layout.buildDirectory.dir("command-logs").get().asFile
logsDir.mkdirs()
// Helper to run pull + command set for a given target (artifact or coordinates)
def runPhaseForCoordinate = { String coordinate ->
// Clean project before pulling Docker images for this coordinate
// Note: 'clean' deletes the build/ directory, so log to a temporary location outside build/,
// then move/copy the log into build/ afterwards.
def tmpCleanLogsDir = new File(project.rootDir, ".tmp-command-logs-clean")
tmpCleanLogsDir.mkdirs()
def fileSuffix = sanitizeFileName(coordinate)
def tmpCleanLogFile = new File(tmpCleanLogsDir, "clean-${fileSuffix}.log")
try {
runGradleTaskAndCheck(
[gradleCmd, "clean", "-Pcoordinates=${coordinate}"],
"clean (${coordinate})",
tmpCleanLogFile
)
} finally {
// After clean, move/copy the log into the build folder (clean wipes build/)
def cleanLogsDir = layout.buildDirectory.dir("command-logs-clean").get().asFile
cleanLogsDir.mkdirs()
def cleanLogFile = new File(cleanLogsDir, "clean-${fileSuffix}.log")
try {
Files.move(tmpCleanLogFile.toPath(), cleanLogFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
} catch (Throwable ignored) {
if (tmpCleanLogFile?.exists()) {
cleanLogFile.text = tmpCleanLogFile.text
}
}
}
// Ensure logsDir exists after clean
logsDir.mkdirs()
// Pull Docker images sequentially for this coordinate
def pullArgs = [gradleCmd, "pullAllowedDockerImages", "-Pcoordinates=${coordinate}"]
def pullLogFile = new File(logsDir, "pullAllowedDockerImages-${fileSuffix}.log")
runGradleTaskAndCheck(pullArgs, "pullAllowedDockerImages (${coordinate})", pullLogFile)
def commands = testInfraCommands(gradleCmd, coordinate)
int effectiveParallelism = Math.min(parallelism, commands.size())
def pool = Executors.newFixedThreadPool(effectiveParallelism)
runCommandsWithPool(pool, coordinate, commands)
}
runPhaseForCoordinate(coordinateProp)
}
}
// Full infra end-to-end entry point (coordinate + 1/64 shard). §AR-test-harness
tasks.register('testAllInfra') { t ->
t.group = "verification"
t.setDescription("Determines one artifact coordinate via generateInfrastructureChangedCoordinatesMatrix (or uses -Pcoordinate/-Pcoordinates if provided), then runs testInfra for that coordinate and also for 1/64. Options: -Pparallelism to control concurrency.")
doLast {
def gradleCmd = System.getProperty("os.name").toLowerCase().contains("windows") ? "gradlew.bat" : "./gradlew"
int parallelism = parsePositiveIntProp('parallelism', 4)
println("Using parallelism=${parallelism} for testAllInfra.")
String artifactCoordinate = ((project.findProperty('coordinate') ?: project.findProperty('coordinates')) ?: '').toString().trim()
if (artifactCoordinate.isEmpty()) {
def matrixLogsDir = layout.buildDirectory.dir("command-logs").get().asFile
matrixLogsDir.mkdirs()
def matrixLog = runGenerateMatrixAndCheck(gradleCmd, matrixLogsDir)
try {
def line = matrixLog.readLines().find { it.startsWith("matrix=") }
if (line != null) {
def jsonStr = line.substring("matrix=".length())
def parsed = new JsonSlurper().parseText(jsonStr)
def coords = (parsed["coordinates"] as List) ?: []
if (coords.isEmpty()) {
coords = ((parsed["include"] as List) ?: [])
.collect { it instanceof Map ? it["coordinates"] : null }
.findAll { it != null }
}
if (!coords.isEmpty()) {
artifactCoordinate = coords[0].toString()
}
}
} catch (Throwable e) {
throw new GradleException("Failed to parse matrix output from ${matrixLog}: ${e.message}")
}
if (!artifactCoordinate) {
throw new GradleException("No coordinates found in generateInfrastructureChangedCoordinatesMatrix output. Provide -Pcoordinate or -Pcoordinates to override.")
}
}
println("Selected artifact coordinate: ${artifactCoordinate}")
def logsDir = layout.buildDirectory.dir("command-logs").get().asFile
logsDir.mkdirs()
def runTestInfraAndCheck = { String coordinate, String gradleCmdParam, int parallelismParam, File logsDirParam, def layoutParam ->
def logFile = new File(logsDirParam, "testInfra-${sanitizeFileName(coordinate)}.log")
runGradleTaskAndCheck(
[gradleCmdParam, "testInfra", "-Pcoordinate=${coordinate}", "-Pparallelism=${parallelismParam}"],
"testInfra (${coordinate})",
logFile
)
}
runTestInfraAndCheck(artifactCoordinate, gradleCmd, parallelism, logsDir, layout)
def batchCoordinate = "1/64"
runTestInfraAndCheck(batchCoordinate, gradleCmd, parallelism, logsDir, layout)
println("testAllInfra completed successfully.")
}
}
/**
* Runs a Gradle task with logging and throws GradleException on non-zero exit.
*
* @param args Full command (gradle executable plus task and its arguments)
* @param label Human-readable label used in logs
* @param logFile Destination log file
* @return The exit code of the process (also throws on non-zero)
*/
def runGradleTaskAndCheck(List<String> args, String label, File logFile) {
int exit = runLoggedCommand(args, label, logFile, project.rootDir)
if (exit != 0) {
throw new GradleException("${label} failed with exit code ${exit} (see ${logFile})")
}
return exit
}
/**
* Runs generateInfrastructureChangedCoordinatesMatrix and returns the log file.
*
* @param gradleCmd Gradle executable path (e.g., "./gradlew" or "gradlew.bat")
* @param logsDir Directory where the log will be written
* @return The File pointing to the generated matrix log
*/
def runGenerateMatrixAndCheck(String gradleCmd, File logsDir) {
logsDir.mkdirs()
def logFile = new File(logsDir, "generateInfrastructureChangedCoordinatesMatrix.log")
runGradleTaskAndCheck(
[gradleCmd, "generateInfrastructureChangedCoordinatesMatrix"],
"generateInfrastructureChangedCoordinatesMatrix",
logFile
)
return logFile
}
/**
* Executes an external command, logs its output to both the console and a dedicated file,
* and returns the exit code. Prepends and appends custom headers and footers to the log
* indicating success or failure.
*
* Behavior:
* - Prints a header to both console and log file before running the command.
* - Ensures parent directories for the log file exist, and overwrites the file with the header.
* - Runs the provided command in a specified working directory, logging both stdout and stderr to the file.
* - Waits for the process to finish and captures its exit code.
* - Appends a footer line to both console and log to indicate SUCCESS or FAILURE, including the exit code if failed.
* - Returns the process exit code to the caller.
*
* @param args The command as a list of strings (executable plus arguments).
* @param label A label for this invocation, included in the header/footer.
* @param logFile File to which all output is logged (will be created/overwritten).
* @param workingDir Directory in which to execute the process.
* @return The exit code of the process.
*/
def runLoggedCommand(List<String> args, String label, File logFile, File workingDir) {
def startTime = new Date().format("yyyy-MM-dd HH:mm:ss")
def header = "==== [${startTime}] BEGIN ${label} logged at ${logFile.absolutePath}"
println(header)
if (logFile?.parentFile) {
logFile.parentFile.mkdirs()
}
logFile.text = header + System.lineSeparator()
def pb = new ProcessBuilder(args as String[])
pb.directory(workingDir)
String nativeImageMode = resolveSelectedNativeImageMode()
if (nativeImageMode != null && !nativeImageMode.trim().isEmpty()) {
pb.environment().put("GVM_TCK_NATIVE_IMAGE_MODE", nativeImageMode)
}
pb.redirectErrorStream(true)
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile))
def proc = pb.start()
int exit = proc.waitFor()
def endTime = new Date().format("yyyy-MM-dd HH:mm:ss")
def footer = exit != 0
? "==== [${endTime}] END ${label} FAILURE (exit ${exit}) logged at ${logFile.absolutePath}"
: "==== [${endTime}] END ${label} SUCCESS logged at ${logFile.absolutePath}"
if (exit != 0) {
println("Failure log for ${label}")
try {
if (logFile?.exists()) {
logFile.eachLine { println(it) }
} else {
println("(log file not found)")
}
} catch (Throwable e) {
println("Error reading ${logFile}: ${e.message}")
}
}
logFile.append(footer + System.lineSeparator())
println(footer)
return exit
}
/**
* Runs a set of external commands concurrently using the provided ExecutorService, writing
* per-command logs under build/command-logs and aggregating failures.
*
* Behavior:
* - Submits each command to the pool via submit(Callable) and waits for all futures to complete.
* - Shuts down the pool and awaits termination for up to 1 hour.
* - On any non-zero exit, prints a summary and the contents of the failed logs, then throws a GradleException.
* - On success, prints a summary message indicating the logs directory.
*
* @param coordinate A label used for log file names and messages (e.g., an artifact coordinate or a batch like 1/64).
* @param commands List of maps representing commands to run; each entry must contain:
* - name: String task label (e.g., "checkstyle")
* - args: List<String> full process arguments passed to ProcessBuilder
* @param pool ExecutorService used to run the commands concurrently; this method will call
* shutdown() and awaitTermination(...) on it.
* @throws GradleException if any command exits with a non-zero status.
*/
def runCommandsWithPool(ExecutorService pool, String coordinate, List<Map> commands) {
def logsDir = layout.buildDirectory.dir("command-logs").get().asFile
logsDir.mkdirs()
def fileSuffix = sanitizeFileName(coordinate)
def failures = Collections.synchronizedList(new ArrayList<Map>())
def futures = []
commands.each { cmd ->
futures << pool.submit {
def label = "${cmd.name} (${coordinate})"
def logFile = new File(logsDir, "${cmd.name}-${fileSuffix}.log")
int exit = runLoggedCommand(cmd.args, label, logFile, project.rootDir)
if (exit != 0) {
failures.add([label: label, logFile: logFile, exit: exit])
}
}
}
futures.each { it.get() }
pool.shutdown()
pool.awaitTermination(1, TimeUnit.HOURS)
if (!failures.isEmpty()) {
println("Some commands failed (coordinates=${coordinate}). Logs in: ${logsDir}")
failures.each { f ->
println(" - ${f.label} failed with exit code ${f.exit} (see ${f.logFile})")
}
println("==== BEGIN FAILED TASK LOGS (${coordinate})")
failures.each { f ->
println("---- LOG: ${f.logFile}")
try {
if (f.logFile?.exists()) {
f.logFile.eachLine { println(it) }
} else {
println("(log file not found)")
}
} catch (Throwable e) {
println("Error reading ${f.logFile}: ${e.message}")
}
}
println("==== END FAILED TASK LOGS (${coordinate})")
throw new GradleException("Failures encountered. See logs above. Logs directory: ${logsDir}")
} else {
println("All commands succeeded for coordinates=${coordinate}. Logs in: ${logsDir}")
}
}
/**
* Parses a project property as a positive integer, returning defaultValue if empty.
* Throws GradleException for invalid or non-positive values.
*/
def parsePositiveIntProp(String propertyName, int defaultValue) {
def prop = (project.findProperty(propertyName) ?: '').toString().trim()
int value = defaultValue
if (!prop.isEmpty()) {
try {
value = Integer.parseInt(prop)
} catch (NumberFormatException ignored) {
throw new GradleException("Invalid -P${propertyName}='${prop}': must be a positive integer.")
}
if (value <= 0) {
throw new GradleException("Invalid -P${propertyName}='${prop}': must be >= 1.")
}
}
return value
}
/*
* Helper utilities for environment setup, and backup/restore
* used by testMetadataGeneration.
*/
def withUnsetTckDir(List<String> baseArgs) {
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
["cmd.exe", "/d", "/c", "set GVM_TCK_TCKDIR= && " + baseArgs.join(' ')]
} else {
["/usr/bin/env", "-u", "GVM_TCK_TCKDIR"] + baseArgs
}
}
def backupDirIfExists(File srcDir, File backupDir) {
boolean had = srcDir?.isDirectory()
if (had) {
backupDir.parentFile?.mkdirs()
project.copy {
from(srcDir)
into(backupDir)
}
}
had
}
def restoreDir(boolean had, File srcDir, File backupDir) {
if (had) {
project.delete(srcDir)
srcDir.mkdirs()
project.copy {
from(backupDir)
into(srcDir)
}
} else {
project.delete(srcDir)
}
}
def backupFileIfExists(File srcFile, File backupFile) {
boolean had = srcFile?.isFile()
if (had) {
backupFile.parentFile?.mkdirs()
backupFile.text = srcFile.getText('UTF-8')
}
had
}
def restoreFileIfBackedUp(boolean had, File srcFile, File backupFile) {
if (had && backupFile?.isFile()) {
srcFile.text = backupFile.getText('UTF-8')
}
}
// Test metadata generation tasks
def testMetadataGeneration(String coordinate, String gradleCmd, File logsDir, String newVersion) {
def fileSuffix = coordinate.replaceAll(File.separator, "-")
// Compute paths and snapshot current state to allow revert after the test
def parts = coordinate.split(":")
if (parts.length != 3) {
throw new GradleException("Invalid coordinates '${coordinate}'. Expected 'group:artifact:version'.")
}
def group = parts[0]
def artifact = parts[1]
def version = parts[2]
def gaPath = "${group}/${artifact}"
def versionPath = "${gaPath}/${version}"
def versionDir = new File(tck.metadataRoot.get().asFile, versionPath)
def testsDir = new File(tck.testRoot.get().asFile, versionPath)
def backupRoot = layout.buildDirectory.dir("gm-backups/${fileSuffix}").get().asFile
def backupMetadataDir = new File(backupRoot, "metadata-backup")
def backupTestsDir = new File(backupRoot, "tests-backup")
backupRoot.mkdirs()
boolean hadVersionDir = backupDirIfExists(versionDir, backupMetadataDir)
boolean hadTestsDir = backupDirIfExists(testsDir, backupTestsDir)
try {
// Build base args once, then prepend an OS-specific unset of GVM_TCK_TCKDIR
def baseGenArgs = [gradleCmd, "generateMetadata", "-Pcoordinates=${coordinate}", "--agentAllowedPackages=org.postgresql"]
List<String> genArgs = withUnsetTckDir(baseGenArgs)
def genLogFile = new File(logsDir, "generateMetadata-${fileSuffix}.log")
int genExit = project.ext.runLoggedCommand(genArgs, "generateMetadata (${coordinate})", genLogFile, project.rootDir)
if (genExit != 0) {
throw new GradleException("generateMetadata failed with exit code ${genExit} (see ${genLogFile})")
}
// Verify output directory for the specific version
if (!versionDir.isDirectory()) {
throw new GradleException("Version directory not found: ${versionDir}")
}
def actualFiles = versionDir.listFiles()?.findAll { it.isFile() }?.collect { it.name }?.sort() ?: []
if (actualFiles.isEmpty()) {
throw new GradleException("No metadata files found in ${versionDir}")
}
println("Verified generated metadata for ${coordinate}: ${versionDir}")
} finally {
// Revert metadata directory changes
restoreDir(hadVersionDir, versionDir, backupMetadataDir)
// Revert tests directory changes (including build.gradle and user-code-filter.json)
restoreDir(hadTestsDir, testsDir, backupTestsDir)
// Cleanup backups
project.delete(backupRoot)
}
def newVersionDir = new File(tck.metadataRoot.get().asFile, "${gaPath}/${newVersion}")
def moduleIndexFile = new File(tck.metadataRoot.get().asFile, "${gaPath}/index.json")
def fixBackupRoot = layout.buildDirectory.dir("fixnir-backups/${fileSuffix}").get().asFile
def backupNewMetadataDir = new File(fixBackupRoot, "new-metadata-backup")
def fixBackupTestsDir = new File(fixBackupRoot, "new-metadata-backup")
def backupModuleIndexFile = new File(fixBackupRoot, "module-index.json.bak")
fixBackupRoot.mkdirs()
hadTestsDir = backupDirIfExists(testsDir, fixBackupTestsDir)
def hadNewVersionDir = backupDirIfExists(newVersionDir, backupNewMetadataDir)
def hadModuleIndexFile = backupFileIfExists(moduleIndexFile, backupModuleIndexFile)
try {
def baseFixArgs = [gradleCmd, "fixTestNativeImageRun", "-PtestLibraryCoordinates=${coordinate}", "-PnewLibraryVersion=${newVersion}"]
List<String> fixArgs = withUnsetTckDir(baseFixArgs)
def fixLogFile = new File(logsDir, "fixTestNativeImageRun-${fileSuffix}.log")
int fixExit = project.ext.runLoggedCommand(fixArgs, "fixTestNativeImageRun (${coordinate} -> ${newVersion})", fixLogFile, project.rootDir)
if (fixExit != 0) {
throw new GradleException("fixTestNativeImageRun failed with exit code ${fixExit} (see ${fixLogFile})")
}
} finally {
// Revert changes
restoreDir(hadNewVersionDir, newVersionDir, backupNewMetadataDir)
restoreDir(hadTestsDir, testsDir, fixBackupTestsDir)
restoreFileIfBackedUp(hadModuleIndexFile, moduleIndexFile, backupModuleIndexFile)
// Cleanup backups
project.delete(fixBackupRoot)
}
}
private static String sanitizeFileName(String coordinate) {
coordinate.replaceAll(File.separator, "-").replaceAll(":", "-")
}