Repository navigation
Expand file tree
/
Copy pathbuild.gradle
More file actions
791 lines (683 loc) · 28.6 KB
/
Copy pathbuild.gradle
File metadata and controls
791 lines (683 loc) · 28.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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
/*
* Copyright 2026 IBM Corporation and others.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
import groovy.time.TimeCategory
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:4.1.0'
}
}
plugins {
id "biz.aQute.bnd.builder" version "6.4.0" apply false
id "com.dorongold.task-tree" version "2.1.1"
id "base"
}
wrapper {
distributionType = Wrapper.DistributionType.ALL
}
// Validate that .sdkmanrc Gradle version matches wrapper version
def validateGradleVersions() {
def sdkmanrcFile = file('.sdkmanrc')
def wrapperPropsFile = file('gradle/wrapper/gradle-wrapper.properties')
if (!sdkmanrcFile.exists()) {
logger.warn("Warning: .sdkmanrc file not found")
return
}
if (!wrapperPropsFile.exists()) {
throw new GradleException("gradle-wrapper.properties not found")
}
// Parse .sdkmanrc for gradle version
def sdkmanrcVersion = null
sdkmanrcFile.eachLine { line ->
if (line.trim().startsWith('gradle=')) {
sdkmanrcVersion = line.split('=')[1].trim()
}
}
// Parse wrapper properties for gradle version
def wrapperVersion = null
wrapperPropsFile.eachLine { line ->
if (line.trim().startsWith('distributionUrl=')) {
def matcher = (line =~ /gradle-(\d+\.\d+(?:\.\d+)?)-/)
if (matcher.find()) {
wrapperVersion = matcher.group(1)
}
}
}
if (sdkmanrcVersion && wrapperVersion) {
if (sdkmanrcVersion != wrapperVersion) {
throw new GradleException(
"Gradle version mismatch!\n" +
" .sdkmanrc: gradle=${sdkmanrcVersion}\n" +
" gradle-wrapper.properties: gradle-${wrapperVersion}\n" +
"Please update both files to use the same Gradle version."
)
}
logger.quiet("✓ Gradle version validated: ${wrapperVersion}")
}
}
// Run validation during configuration phase
validateGradleVersions()
// Apply interop testing tasks
apply from: 'config/gradle/interop-testing.gradle'
// Apply release configuration
apply from: 'config/gradle/build-release.gradle'
// compute git hash
import static java.time.format.DateTimeFormatter.BASIC_ISO_DATE
import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME
def gitHash = 'git rev-parse HEAD'.execute().text.trim()
def gitDirty = !'git status --porcelain'.execute().text.trim().isEmpty()
// compute git commit date
def gitIsoDate = 'git log -1 --date=iso-strict --pretty=format:%cd'.execute().text.trim()
// convert from author's time zone to UTC
def gitIsoDateUtc = Instant.from(ISO_OFFSET_DATE_TIME.parse(gitIsoDate)).atZone(ZoneOffset.UTC)
def gitBasicDateUtc = BASIC_ISO_DATE.format(gitIsoDateUtc)
// Although SemVer2.0 prescribes '+' and '-' separators after major.minor.patch
// OSGi mandates major.minor.patch.qualifier
// OSGi permits '-' and '_' within the qualifier, but not at either end
// OSGi permits no other punctuation or whitespace
// Version detection: use the semantic version tag on HEAD, or fall back to "dev".
def baseVersion
try {
def tagsOutput = 'git tag --points-at HEAD'.execute().text.trim()
if (tagsOutput) {
def versionPattern = /^v?(\d+\.\d+\.\d+)$/
def versionTags = tagsOutput.split('\n')
.findAll { it =~ versionPattern }
.collect { tag ->
def matcher = tag =~ versionPattern
matcher.matches() ? matcher.group(1) : null
}
.findAll { it != null }
if (!versionTags.isEmpty()) {
if (versionTags.size() > 1) {
throw new GradleException(
"Multiple version tags found on HEAD: ${versionTags.join(', ')}\n" +
"Remove the extra tags and re-run."
)
}
baseVersion = versionTags[0]
logger.quiet("Using version from git tag on HEAD: ${baseVersion}")
} else {
baseVersion = 'dev'
logger.quiet("No version tag on HEAD, using: ${baseVersion}")
}
} else {
baseVersion = 'dev'
logger.quiet("No git tags on HEAD, using: ${baseVersion}")
}
} catch (GradleException e) {
throw e
} catch (Exception e) {
baseVersion = 'dev'
logger.warn("Failed to read git tags (${e.message}), using: ${baseVersion}")
}
ext.baseVersion = baseVersion
def yokoVersion = (baseVersion == 'dev')
? "0.0.0.dev_${gitBasicDateUtc.take(8)}_${gitHash.take(10)}${gitDirty ? '_dirty' : ''}"
: "${baseVersion}.${gitBasicDateUtc.take(8)}_${gitHash.take(10)}${gitDirty ? '_dirty' : ''}"
// set system properties for use in bundle metadata
System.setProperty("git.hash", gitHash);
System.setProperty("git.date", gitIsoDateUtc.toString());
task getVersion {
printf "Yoko version = %s%n", yokoVersion
}
// These are the production projects.
// Note the ringer: jdk-supplement is an unshipped prereq to allow compiling for Java 8 and running with Java 11.
// Stored in ext so it is reachable from script methods (a bare def is not).
ext.productionProjectPaths = [':jdk-supplement', ':yoko-osgi', ':yoko-spec-corba', ':yoko-rmi-spec', ':yoko-util', ':yoko-rmi-impl', ':yoko-core']
/* Standard configuration for each subproject */
subprojects { sp ->
apply plugin: 'java-library'
// Production projects MUST compile for Java 8
// Test projects are now Java 11 and up only.
sourceCompatibility = targetCompatibility = productionProjectPaths.contains(sp.path) ? 1.8 : 11
// Use Java 11 for all unit test compilation too
tasks.withType(JavaCompile).configureEach {if (name.toLowerCase().contains('test')) sourceCompatibility = targetCompatibility = 11 }
repositories {
mavenLocal()
mavenCentral()
}
configurations {
// declare a test library configuration
testLib
testImplementation.extendsFrom testLib
}
// additional configuration for projects that have bnd.bnd files
if (sp.file("bnd.bnd").exists()) {
apply plugin: 'biz.aQute.bnd.builder'
// to extend the project with a new property, use project.ext.<new property name>
project.ext.symbolicName = project.name.replaceFirst("^yoko-", symbolicNamePrefix)
version = yokoVersion
}
// standardise the test deps here
dependencies {
testLib 'junit:junit:4.12'
testLib 'org.mockito:mockito-core:5.18.0'
testLib 'org.mockito:mockito-junit-jupiter:5.18.0'
testLib "org.hamcrest:hamcrest:2.1"
testLib "org.junit.jupiter:junit-jupiter:5.9.0"
testLib "org.junit.platform:junit-platform-runner:1.8.2"
testLib "org.junit-pioneer:junit-pioneer:1.9.1"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.9.0"
testRuntimeOnly "org.junit.vintage:junit-vintage-engine:5.9.0"
}
if (JavaVersion.current() < JavaVersion.VERSION_11) {
throw new GradleException("This build must be run with java 11 or higher")
}
// ensure tests run under $buildDir somewhere
tasks.withType(Test).configureEach {
jvmArgs '--add-opens=java.base/java.lang=ALL-UNNAMED'
jvmArgs '--add-opens=java.base/java.lang.invoke=ALL-UNNAMED'
jvmArgs '--add-opens=java.base/java.io=ALL-UNNAMED'
jvmArgs '--add-opens=java.base/java.util=ALL-UNNAMED'
jvmArgs '--add-opens=java.rmi/java.rmi=ALL-UNNAMED'
useJUnitPlatform {
// Support excluding tags via system property (e.g., -Dtest.excludeTags=interop)
def tagsToExclude = System.getProperty('test.excludeTags')
if (tagsToExclude) {
tagsToExclude.split(',').each { tag ->
excludeTags tag.trim()
}
}
}
workingDir = "$buildDir/testWorkingDir"
doFirst {workingDir.mkdirs()}
testLogging {
// set options for log level LIFECYCLE
events "skipped", "failed", "passed", "standardOut"
showExceptions true
exceptionFormat "full"
showCauses true
showStackTraces true
// set options for log level DEBUG and INFO
debug {
events "skipped", "failed", "started", "passed", "standardOut", "standardError"
exceptionFormat "full"
}
info.events = debug.events
info.exceptionFormat = debug.exceptionFormat
ignoreFailures = true // Always try to run all tests for all modules
afterTest { desc, result ->
def totalTime = result.endTime - result.startTime
println """"Test elapsed time","$desc.name",$totalTime"""
}
afterSuite { desc, result ->
if (!desc.parent) { // will match the outermost suite
def timeTaken = TimeCategory.minus(new Date(result.endTime), new Date(result.startTime))
def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
def startItem = '| ', endItem = ' |'
def repeatLength = startItem.length() + output.length() + endItem.length()
println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength))
}
def totalTime = result.endTime - result.startTime
println """"Suite elapsed time","$desc.name",$totalTime"""
}
}
reports {
junitXml.required = true
html.required = true
}
}
}
/* Standard configuration for subprojects with shippable outputs */
configure([
project(':yoko-osgi'),
project(':yoko-util'),
project(':yoko-spec-corba'),
project(':yoko-rmi-spec'),
project(':yoko-rmi-impl'),
project(':yoko-core'),
project(':testify'),
]) {
apply plugin: 'maven-publish'
publishing {
publications {
maven(MavenPublication) {
artifact jar
pom.withXml {
def rootNode = asNode()
// // specify packaging type as bundle (default is pom)
// def packaging = root.packaging[0] ?:
// root.appendNode('packaging')
// packaging.setValue('bundle')
def depsNode = rootNode.dependencies[0] ?:
rootNode.appendNode('dependencies')
// declare compile scope dependencies in the pom.xml
// as compile dependencies
configurations.implementation.allDependencies.each {
def depNode = depsNode.appendNode('dependency')
depNode.appendNode('groupId', it.group)
depNode.appendNode('artifactId', it.name)
depNode.appendNode('version', it.version)
depNode.appendNode('scope', 'compile')
}
}
}
}
}
jar {
dependsOn "generatePomFileForMavenPublication"
// generate the maven dependency metadata
into("/META-INF/maven/$project.group/$project.name") {
from 'build/publications/maven'
rename "pom-default.xml", "pom.xml"
}
}
publish.dependsOn build
// generated tasks need to be expressed as strings
// because they don't exist yet when these lines are executed
publish.dependsOn "publishMavenPublicationToMavenLocal"
publish.dependsOn "publishToMavenLocal"
}
/**
* Print a one-line-per-module summary of all JUnit XML results found on disk.
* Results pre-dating the compiled test classes (or production jars, for integration
* modules) are flagged [STALE]. Fails the build if any non-stale failures are found.
*
* Run standalone: ./gradlew testSummary
* Wired automatically as a finalizer of the top-level :build task.
*/
task testSummary {
description = 'Summarise test results on disk; fails the build if any (non-stale) tests failed'
group = 'verification'
doLast {
def failures = printTestSummary(project)
if (failures > 0) {
throw new GradleException("${failures} test(s) failed — see FAILING TESTS above")
}
}
}
// Run testSummary automatically after every top-level build
build.finalizedBy testSummary
/**
* Show a time-distribution analysis across all individual test cases on disk.
*
* Lists every test that ran more than 2 standard deviations above the mean.
*
* Run standalone: ./gradlew testTimes
*/
task testTimes {
description = 'Show test-time distribution and list tests > 2 std devs above the mean'
group = 'verification'
doLast {
printTestTimes(project)
}
}
private void printTestTimes(project) {
// Collect every individual testcase time across all modules
def cases = []
project.rootProject.subprojects.each { sp ->
def resultsDir = new File(sp.buildDir, 'test-results')
if (!resultsDir.exists()) return
sp.fileTree(resultsDir) { include '**/TEST-*.xml' }.each { xmlFile ->
def xml = new XmlSlurper().parse(xmlFile)
xml.testcase.each { tc ->
def t = tc.@time.text()
if (!t) return
def timeSec = t.toDouble()
if (timeSec <= 0) return // exclude sub-millisecond tests from the distribution
cases << [
module : sp.name,
clazz : tc.@classname.text(),
name : tc.@name.text(),
timeSec: timeSec,
]
}
}
}
if (cases.isEmpty()) {
project.logger.quiet('\nNo test results found on disk.')
return
}
int n = cases.size()
double mean = cases*.timeSec.sum() / n
double variance = cases*.timeSec.collect { (it - mean) ** 2 }.sum() / n
double sd = Math.sqrt(variance)
double threshold = mean + 2 * sd
def outliers = cases.findAll { it.timeSec > threshold }.sort { -it.timeSec }
def sb = new StringBuilder()
sb << '\n'
sb << '\n Test Time Analysis\n'
sb << sprintf(" %d tests with measurable time | mean %.4fs | sd %.4fs | threshold (mean + 2sd) %.3fs\n",
n, mean, sd, threshold)
if (outliers.isEmpty()) {
sb << '\n No tests exceeded the threshold.\n'
} else {
sb << sprintf("\n %d test(s) more than 2 std devs above the mean (> %.3fs):\n", outliers.size(), threshold)
int wModule = Math.max('Module'.length(), outliers*.module.collect { it.length() }.max())
int wClass = Math.max('Class'.length(), outliers*.clazz .collect { it.length() }.max())
int wName = Math.max('Test'.length(), outliers*.name .collect { it.length() }.max())
def sep = '-' * (wModule + wClass + wName + 18)
def fmt = " %-${wModule}s %-${wClass}s %-${wName}s %8s"
sb << " ${sep}\n"
sb << sprintf(fmt, 'Module', 'Class', 'Test', 'Time(s)') << '\n'
sb << " ${sep}\n"
outliers.each { c ->
sb << sprintf(fmt, c.module, c.clazz, c.name, String.format('%.3f', c.timeSec)) << '\n'
}
sb << " ${sep}\n"
}
project.logger.quiet(sb.toString())
}
private int printTestSummary(project) {
def rp = project.rootProject
// Newest mtime across all production jars — used as an additional staleness anchor
// for integration-test modules that run against the shipped artifacts.
def integrationTestProjects = [':yoko-verify', ':test-osgi'] as Set
// Newest mtime across all production jars (from ext.productionProjectPaths).
// Used as an additional staleness anchor for integration-test modules.
def newestProductionJarMs = -1L
rp.productionProjectPaths.each { path ->
def prod = rp.findProject(path)
if (prod == null) return
prod.fileTree(new File(prod.buildDir, 'libs')) { include '*.jar'; exclude '*-sources.jar'; exclude '*-javadoc.jar' }.each { f ->
if (f.lastModified() > newestProductionJarMs) newestProductionJarMs = f.lastModified()
}
}
// Newest mtime of the versioned artifact jars — only yoko-verify tests depend on these.
def newestArtifactJarMs = -1L
[':yoko-verify:artifact', ':yoko-verify:artifact:v0', ':yoko-verify:artifact:v1', ':yoko-verify:artifact:v2'].each { path ->
def ap = rp.findProject(path)
if (ap == null) return
ap.fileTree(new File(ap.buildDir, 'libs')) { include '*.jar' }.each { f ->
if (f.lastModified() > newestArtifactJarMs) newestArtifactJarMs = f.lastModified()
}
}
// Collect one row per testsuite XML file
def rows = []
rp.subprojects.each { sp ->
def resultsDir = new File(sp.buildDir, 'test-results')
if (!resultsDir.exists()) return
// Compute the staleness anchor for this subproject: the newest mtime among all
// compiled artefacts that the tests depend on.
//
// Class directories are read from the project's sourceSets at execution time so
// that hardcoded paths like 'classes/java/main' vs 'classes/java/test' don't need
// to be maintained here. Every sourceSet's output class dirs are included so that
// a change to production code that hasn't been re-tested is detected as stale.
//
// For integration-test modules (yoko-verify, test-osgi) we additionally require
// results to post-date the newest production and versioned-artifact jar.
def classDirs = []
try {
sp.sourceSets.each { ss -> classDirs.addAll(ss.output.classesDirs.files) }
} catch (Exception ignored) {
// sourceSets not available (e.g. pure-aggregator subproject) — skip
return
}
def newestClassMs = -1L
classDirs.each { dir ->
if (!dir.exists()) return
sp.fileTree(dir) { include '**/*.class' }.each { f ->
if (f.lastModified() > newestClassMs) newestClassMs = f.lastModified()
}
}
// newestClassMs == -1 when no compiled classes exist (e.g. a compile failure left
// stale results on disk). anchorMs of -1 means the staleness comparison will always
// return stale=true, which is the correct conservative answer: we cannot confirm the
// results are fresh, so flag them rather than throwing a misleading second error.
// For integration-test modules also require results to post-date the production jars.
// For yoko-verify specifically, also require results to post-date the versioned artifact jars.
def anchorMs = newestClassMs
if (integrationTestProjects.contains(sp.path) && newestProductionJarMs > anchorMs) {
anchorMs = newestProductionJarMs
}
if (sp.path == ':yoko-verify' && newestArtifactJarMs > anchorMs) {
anchorMs = newestArtifactJarMs
}
// The XML timestamp is truncated to whole seconds; anchorMs is milliseconds.
// Floor the anchor to the second boundary so a suite that started in the same
// second as the newest class file is not incorrectly reported as stale.
def anchorSec = (anchorMs / 1000L) as long
sp.fileTree(resultsDir) { include '**/TEST-*.xml' }.each { xmlFile ->
def xml = new XmlSlurper().parse(xmlFile)
def ts = xml.@tests.text().toInteger()
def failures = xml.@failures.text().toInteger()
def errors = xml.@errors.text().toInteger()
def skipped = xml.@skipped.text().toInteger()
def passed = ts - failures - errors - skipped
def timeVal = xml.@time.text()
def suiteName = xml.@name.text()
def timestamp = xml.@timestamp.text() // e.g. "2026-11-02T14:53:09"
// A result is stale when it pre-dates the anchor timestamp.
// A missing or unparseable timestamp is a broken XML file — fail loudly.
if (!timestamp) {
throw new GradleException(
"Missing timestamp attribute in ${xmlFile.name} (${sp.name}).\n" +
"The file may be corrupt. Delete ${sp.buildDir}/test-results and re-run tests.")
}
def stale
if (anchorMs < 0) {
stale = true // no compiled classes — cannot confirm freshness
} else try {
// Accept both "2026-11-02T14:53:09" (no zone, assumed UTC) and
// "2026-11-05T17:42:27.293Z" (optional fraction and offset), depending on the Gradle version.
def parsed = DateTimeFormatter.ISO_DATE_TIME.parse(timestamp)
def suiteEpochSec = parsed.isSupported(java.time.temporal.ChronoField.OFFSET_SECONDS)
? java.time.OffsetDateTime.from(parsed).toEpochSecond()
: java.time.LocalDateTime.from(parsed).atZone(ZoneOffset.UTC).toEpochSecond()
stale = suiteEpochSec < anchorSec
} catch (Exception e) {
throw new GradleException(
"Unparseable timestamp '${timestamp}' in ${xmlFile.name} (${sp.name}): ${e.message}\n" +
"Expected ISO-8601 format: yyyy-MM-ddTHH:mm:ss[.SSS][Z]")
}
// Collect individual failing test names from this suite
def failingTests = []
if (failures + errors > 0) {
xml.testcase.each { tc ->
if (tc.failure.size() > 0 || tc.error.size() > 0) {
failingTests << "${tc.@classname.text()}.${tc.@name.text()}"
}
}
}
rows << [
path : sp.path,
module : sp.name,
tests : ts,
passed : passed,
failures : failures + errors,
skipped : skipped,
timeSec : timeVal.toDouble(),
stale : stale,
failingTests: failingTests,
]
}
}
if (rows.isEmpty()) {
project.logger.quiet('\nNo test results found on disk.')
return 0
}
// Aggregate to one row per module, keyed on project path (unique) not name
def byModule = [:]
rows.each { r ->
def m = byModule.computeIfAbsent(r.path) { [
module : r.module,
tests : 0,
passed : 0,
failures : 0,
skipped : 0,
timeSec : 0.0,
stale : false,
failingTests : [], // non-stale failures
staleFailingTests: [], // stale failures
]}
m.tests += r.tests
m.passed += r.passed
m.failures += r.failures
m.skipped += r.skipped
m.timeSec += r.timeSec
if (r.stale) {
m.stale = true
m.staleFailingTests.addAll(r.failingTests)
} else {
m.failingTests.addAll(r.failingTests)
}
}
// Sort: stale last, then by module display name
def modules = byModule.values().sort { a, b ->
if (a.stale != b.stale) return a.stale ? 1 : -1
a.module <=> b.module // display name (sp.name) — unique within a flat project structure
}
// Column widths
int wModule = Math.max('Module'.length(), modules*.module.collect { it.length() }.max())
int wTests = Math.max('Tests'.length(), modules*.tests .collect { it.toString().length() }.max())
int wPassed = Math.max('Passed'.length(), modules*.passed .collect { it.toString().length() }.max())
int wFailed = Math.max('Failed'.length(), modules*.failures.collect { it.toString().length() }.max())
int wSkipped = Math.max('Skipped'.length(), modules*.skipped .collect { it.toString().length() }.max())
def sep = '-' * (wModule + wTests + wPassed + wFailed + wSkipped + 24)
def fmt = " %-${wModule}s %${wTests}s %${wPassed}s %${wFailed}s %${wSkipped}s %8s %s"
def sb = new StringBuilder()
sb << '\n'
sb << '\n Test Summary\n'
sb << " ${sep}\n"
sb << sprintf(fmt, 'Module', 'Tests', 'Passed', 'Failed', 'Skipped', 'Time(s)', '') << '\n'
sb << " ${sep}\n"
int totTests = 0, totPassed = 0, totFailed = 0, totSkipped = 0
double totTime = 0.0
modules.each { m ->
def tag = m.stale ? '[STALE]' : ''
def timeStr = String.format('%.3f', m.timeSec)
sb << sprintf(fmt, m.module, m.tests, m.passed, m.failures, m.skipped, timeStr, tag) << '\n'
totTests += m.tests
totPassed += m.passed
totFailed += m.failures
totSkipped += m.skipped
totTime += m.timeSec
}
sb << " ${sep}\n"
sb << sprintf(fmt, 'TOTAL', totTests, totPassed, totFailed, totSkipped, String.format('%.3f', totTime), '') << '\n'
sb << " ${sep}\n"
// Non-stale failures — these will fail the build
def freshFailing = modules.collectMany { m -> m.failingTests.collect { t -> "${m.module} > ${t}" } }
// Stale failures — informational only
def staleFailing = modules.collectMany { m -> m.staleFailingTests.collect { t -> "${m.module} > ${t}" } }
if (freshFailing || staleFailing) {
sb << '\n FAILING TESTS:\n'
freshFailing.each { sb << " ${it}\n" }
staleFailing.each { sb << " ${it} [STALE]\n" }
}
project.logger.quiet(sb.toString())
return freshFailing.size()
}
task testReport (type: TestReport) {
// GitHub artifact uploader won't upload anything in the root project. Not sure why.
// Generate the aggregate report into a subproject
destinationDir = file("${buildDir}/reports/allTests")
def projectsWithResults = subprojects.findAll { subproject ->
def testResultsDir = new File(subproject.buildDir, "test-results")
if (!testResultsDir.exists()) return false
def xmlFiles = subproject.fileTree(testResultsDir).include("**/*.xml")
return !xmlFiles.empty
}
def projectsWithTests = subprojects.findAll { it.tasks.findByName('test') != null }
testResults.from = projectsWithResults.test
}
task createBuildLibSymlinks {
description = 'Creates symbolic links to jar files in the build/lib directory'
group = 'build'
def targetProjects = [
':yoko-core',
':yoko-spec-corba',
':yoko-rmi-impl',
':yoko-rmi-spec',
':yoko-util',
':yoko-osgi'
]
// Depend on jar tasks of all target projects
targetProjects.each { projectPath ->
dependsOn "${projectPath}:jar"
}
// Register output directory so gradle clean removes it
outputs.dir("${buildDir}/lib")
doLast {
def libDir = file("${buildDir}/lib")
def depsDir = file("${buildDir}/lib/deps")
// Create directories if they don't exist
if (!depsDir.exists()) {
depsDir.mkdirs()
println "Created directory: ${depsDir}"
}
// Clean out existing symbolic links and regular files in lib
libDir.listFiles().each { file ->
if (file.isFile() || (java.nio.file.Files.isSymbolicLink(file.toPath()) && file.name.endsWith('.jar'))) {
file.delete()
println "Removed existing file: ${file.name}"
}
}
// Clean out deps directory
if (depsDir.exists()) {
depsDir.listFiles().each { file ->
file.delete()
}
}
// Create symbolic links for each project's jar
targetProjects.each { projectPath ->
def subproject = project(projectPath)
def jarTask = subproject.tasks.jar
def jarFile = jarTask.archiveFile.get().asFile
if (jarFile.exists()) {
// Use simple name without version info
def projectName = subproject.name
def linkFile = new File(libDir, "${projectName}.jar")
// Create symbolic link using relative path
def relativePath = libDir.toPath().relativize(jarFile.toPath())
java.nio.file.Files.createSymbolicLink(
linkFile.toPath(),
relativePath
)
println "Created symlink: ${linkFile.name} -> ${relativePath}"
} else {
println "Warning: JAR file not found: ${jarFile}"
}
}
// Copy external dependencies from yoko-core runtime classpath to deps/
def coreProject = project(':yoko-core')
def runtimeClasspath = coreProject.configurations.runtimeClasspath
def externalDeps = runtimeClasspath.resolvedConfiguration.resolvedArtifacts.findAll { artifact ->
// Only include external dependencies (not project dependencies)
artifact.moduleVersion.id.group != project.group
}
externalDeps.each { artifact ->
def sourceFile = artifact.file
def targetFile = new File(depsDir, sourceFile.name)
// Copy the file to deps/ directory
java.nio.file.Files.copy(
sourceFile.toPath(),
targetFile.toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING
)
println "Copied dependency: ${sourceFile.name} -> deps/"
// Create version-free symlink in lib/ pointing to deps/
def baseName = sourceFile.name.replaceAll(/-\d+(\.\d+)*(-[^.]+)?\.jar$/, '.jar')
def symlinkFile = new File(libDir, baseName)
def symlinkTarget = libDir.toPath().relativize(targetFile.toPath())
java.nio.file.Files.createSymbolicLink(
symlinkFile.toPath(),
symlinkTarget
)
println "Created symlink: ${baseName} -> ${symlinkTarget}"
}
}
}
// Make createBuildLibSymlinks run at the end of build
build.finalizedBy createBuildLibSymlinks