-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathbuild.gradle
More file actions
628 lines (546 loc) · 21 KB
/
build.gradle
File metadata and controls
628 lines (546 loc) · 21 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
import aQute.bnd.gradle.BundleTaskExtension
import net.ltgt.gradle.errorprone.CheckSeverity
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.dsl.KotlinVersion
import java.text.SimpleDateFormat
plugins {
id 'java'
id 'java-library'
id 'maven-publish'
id 'antlr'
id 'signing'
id "com.gradleup.shadow" version "9.3.1"
id "biz.aQute.bnd.builder" version "7.1.0"
id "io.github.gradle-nexus.publish-plugin" version "2.0.0"
id "groovy"
id "me.champeau.jmh" version "0.7.3"
id "net.ltgt.errorprone" version '5.0.0'
id 'jacoco'
//
// Kotlin just for tests - not production code
id 'org.jetbrains.kotlin.jvm' version '2.3.0'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21) // build on 21 - release on 11
}
}
kotlin {
compilerOptions {
apiVersion = KotlinVersion.KOTLIN_2_0
languageVersion = KotlinVersion.KOTLIN_2_0
jvmTarget = JvmTarget.JVM_11
javaParameters = true
freeCompilerArgs = [
'-Xemit-jvm-type-annotations',
'-Xjspecify-annotations=strict',
]
}
}
def makeDevelopmentVersion(parts) {
def version = String.join("-", parts)
println "created development version: $version"
return version
}
def getDevelopmentVersion() {
def dateTime = new SimpleDateFormat('yyyy-MM-dd\'T\'HH-mm-ss').format(new Date())
def gitCheckOutput = new StringBuilder()
def gitCheckError = new StringBuilder()
def gitCheck = ["git", "-C", projectDir.toString(), "rev-parse", "--is-inside-work-tree"].execute()
gitCheck.waitForProcessOutput(gitCheckOutput, gitCheckError)
def isGit = gitCheckOutput.toString().trim()
if (isGit != "true") {
return makeDevelopmentVersion(["0.0.0", dateTime, "no-git"])
}
// a default Github Action env variable set to 'true'
def isCi = Boolean.parseBoolean(System.env.CI)
if (isCi) {
def gitHashOutput = new StringBuilder()
def gitHashError = new StringBuilder()
def gitShortHash = ["git", "-C", projectDir.toString(), "rev-parse", "--short", "HEAD"].execute()
gitShortHash.waitForProcessOutput(gitHashOutput, gitHashError)
def gitHash = gitHashOutput.toString().trim()
if (gitHash.isEmpty()) {
println "git hash is empty: error: ${gitHashError.toString()}"
throw new IllegalStateException("git hash could not be determined")
}
return makeDevelopmentVersion(["0.0.0", dateTime, gitHash])
}
def gitRevParseOutput = new StringBuilder()
def gitRevParseError = new StringBuilder()
def gitRevParse = ["git", "-C", projectDir.toString(), "rev-parse", "--abbrev-ref", "HEAD"].execute()
gitRevParse.waitForProcessOutput(gitRevParseOutput, gitRevParseError)
def branchName = gitRevParseOutput.toString().trim().replaceAll('[/\\\\]', '-')
return makeDevelopmentVersion(["0.0.0", branchName, "SNAPSHOT"])
}
def reactiveStreamsVersion = '1.0.3'
def releaseVersion = System.env.RELEASE_VERSION
def antlrVersion = '4.13.2' // https://mvnrepository.com/artifact/org.antlr/antlr4-runtime
def guavaVersion = '32.1.2-jre'
version = releaseVersion ? releaseVersion : getDevelopmentVersion()
group = 'com.graphql-java'
gradle.buildFinished { buildResult ->
println "*******************************"
println "*"
if (buildResult.failure != null) {
println "* FAILURE - ${buildResult.failure}"
} else {
println "* SUCCESS"
}
println "* Version: $version"
println "*"
println "*******************************"
}
repositories {
mavenCentral()
mavenLocal()
}
jar {
from "LICENSE.md"
from "src/main/antlr/Graphql.g4"
from "src/main/antlr/GraphqlOperation.g4"
from "src/main/antlr/GraphqlSDL.g4"
from "src/main/antlr/GraphqlCommon.g4"
manifest {
attributes('Automatic-Module-Name': 'com.graphqljava')
}
}
dependencies {
api 'com.graphql-java:java-dataloader:6.0.0'
api 'org.reactivestreams:reactive-streams:' + reactiveStreamsVersion
api "org.jspecify:jspecify:1.0.0"
implementation 'org.antlr:antlr4-runtime:' + antlrVersion
implementation 'com.google.guava:guava:' + guavaVersion
testImplementation 'org.junit.jupiter:junit-jupiter:5.14.1'
testImplementation 'org.spockframework:spock-core:2.4-groovy-5.0'
testImplementation 'net.bytebuddy:byte-buddy:1.18.5'
testImplementation 'org.objenesis:objenesis:3.5'
testImplementation 'org.apache.groovy:groovy:5.0.4'
testImplementation 'org.apache.groovy:groovy-json:5.0.4'
testImplementation 'com.google.code.gson:gson:2.13.2'
testImplementation 'org.eclipse.jetty:jetty-server:11.0.26'
testImplementation 'com.fasterxml.jackson.core:jackson-databind:2.21.1'
testImplementation 'org.awaitility:awaitility-groovy:4.3.0'
testImplementation 'com.github.javafaker:javafaker:1.0.2'
testImplementation 'org.reactivestreams:reactive-streams-tck:' + reactiveStreamsVersion
testImplementation "io.reactivex.rxjava2:rxjava:2.2.21"
testImplementation "io.projectreactor:reactor-core:3.8.0"
testImplementation 'org.testng:testng:7.12.0' // use for reactive streams test inheritance
testImplementation "com.tngtech.archunit:archunit-junit5:1.4.1"
testImplementation 'org.openjdk.jmh:jmh-core:1.37' // required for ArchUnit to check JMH tests
// JUnit Platform launcher required for Gradle 9
testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.14.1'
antlr 'org.antlr:antlr4:' + antlrVersion
// this is needed for the idea jmh plugin to work correctly
jmh 'org.openjdk.jmh:jmh-core:1.37'
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.37'
jmh 'me.bechberger:ap-loader-all:4.3-12'
// comment this in if you want to run JMH benchmarks from idea
// jmhAnnotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess:1.37'
errorprone 'com.uber.nullaway:nullaway:0.12.10'
errorprone 'com.google.errorprone:error_prone_core:2.47.0'
// just tests - no Kotlin otherwise
testImplementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
shadowJar {
minimize()
archiveClassifier.set('')
configurations = [project.configurations.compileClasspath]
relocate('com.google.common', 'graphql.com.google.common') {
include 'com.google.common.collect.*'
include 'com.google.common.base.*'
include 'com.google.common.math.*'
include 'com.google.common.primitives.*'
}
relocate('org.antlr.v4.runtime', 'graphql.org.antlr.v4.runtime')
dependencies {
include(dependency('com.google.guava:guava:' + guavaVersion))
include(dependency('org.antlr:antlr4-runtime:' + antlrVersion))
}
from "LICENSE.md"
from "src/main/antlr/Graphql.g4"
from "src/main/antlr/GraphqlOperation.g4"
from "src/main/antlr/GraphqlSDL.g4"
from "src/main/antlr/GraphqlCommon.g4"
manifest {
attributes('Automatic-Module-Name': 'com.graphqljava')
}
}
// Apply bnd to shadowJar task manually for Gradle 9 compatibility
tasks.named('shadowJar').configure {
// Get the BundleTaskExtension added by bnd plugin
def bundle = extensions.findByType(BundleTaskExtension)
if (bundle != null) {
//Configure bnd for shadowJar
// -exportcontents: graphql.* Adds all packages of graphql and below to the exported packages list
// -removeheaders: Private-Package Removes the MANIFEST.MF header Private-Package, which contains all the internal packages and
// also the repackaged packages like guava, which would be wrong after repackaging.
// Import-Package: Changes the imported packages header, to exclude guava and dependencies from the import list (! excludes packages)
// Guava was repackaged and included inside the jar, so we need to remove it.
// ANTLR was shaded, so we need to remove it.
// sun.misc is a JRE internal-only class that is not directly used by graphql-java. It was causing problems in libraries using graphql-java.
// The last ,* copies all the existing imports from the other dependencies, which is required.
bundle.bnd('''
-exportcontents: graphql.*
-removeheaders: Private-Package
Import-Package: !android.os.*,!com.google.*,!org.checkerframework.*,!graphql.com.google.*,!org.antlr.*,!graphql.org.antlr.*,!sun.misc.*,org.jspecify.annotations;resolution:=optional,*
''')
}
}
tasks.named('jmhJar') {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from {
project.configurations.jmhRuntimeClasspath
.filter { it.exists() }
.collect { it.isDirectory() ? it : zipTree(it) }
}
}
jmh {
if (project.hasProperty('jmhInclude')) {
includes = [project.property('jmhInclude')]
}
if (project.hasProperty('jmhProfilers')) {
def profStr = project.property('jmhProfilers') as String
if (profStr.startsWith('async')) {
// Resolve native lib from ap-loader JAR on the jmh classpath
def apJar = configurations.jmh.files.find { it.name.contains('ap-loader') }
if (apJar) {
def proc = ['java', '-jar', apJar.absolutePath, 'agentpath'].execute()
proc.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)
def libPath = proc.text.trim()
if (libPath && new File(libPath).exists()) {
if (profStr == 'async') {
profilers = ["async:libPath=${libPath}"]
} else {
profilers = [profStr.replaceFirst('async:', "async:libPath=${libPath};")]
}
} else {
profilers = [profStr]
}
} else {
profilers = [profStr]
}
} else {
profilers = [profStr]
}
}
if (project.hasProperty('jmhFork')) {
fork = project.property('jmhFork') as int
}
if (project.hasProperty('jmhIterations')) {
iterations = project.property('jmhIterations') as int
}
if (project.hasProperty('jmhWarmupIterations')) {
warmupIterations = project.property('jmhWarmupIterations') as int
}
}
task extractWithoutGuava(type: Copy) {
from({ zipTree({ "build/libs/graphql-java-${project.version}.jar" }) }) {
exclude('/com/**')
}
into layout.buildDirectory.dir("extract")
}
extractWithoutGuava.dependsOn jar
task buildNewJar(type: Jar) {
from layout.buildDirectory.dir("extract")
archiveFileName = "graphql-java-tmp.jar"
destinationDirectory = file("${project.buildDir}/libs")
manifest {
from file("build/extract/META-INF/MANIFEST.MF")
}
def projectVersion = version
doLast {
delete("build/libs/graphql-java-${projectVersion}.jar")
file("build/libs/graphql-java-tmp.jar").renameTo(file("build/libs/graphql-java-${projectVersion}.jar"))
}
}
buildNewJar.dependsOn extractWithoutGuava
shadowJar.finalizedBy extractWithoutGuava, buildNewJar
task testng(type: Test) {
useTestNG()
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
dependsOn tasks.named('testClasses')
}
check.dependsOn testng
compileJava {
options.compilerArgs += ["-parameters"]
source file("build/generated-src"), sourceSets.main.java
// Gradle 9 requires explicit task dependencies
mustRunAfter generateTestGrammarSource, generateJmhGrammarSource
}
tasks.withType(GroovyCompile) {
// Options when compiling Java using the Groovy plugin.
// (Groovy itself defaults to UTF-8 for Groovy code)
options.encoding = 'UTF-8'
sourceCompatibility = '11'
targetCompatibility = '11'
groovyOptions.forkOptions.memoryMaximumSize = "4g"
}
tasks.withType(JavaCompile) {
options.release = 11
options.errorprone {
disableAllChecks = true
check("NullAway", CheckSeverity.ERROR)
//
// end state has us with this config turned on - eg all classes
//
//option("NullAway:AnnotatedPackages", "graphql")
option("NullAway:CustomContractAnnotations", "graphql.Contract")
option("NullAway:OnlyNullMarked", "true")
option("NullAway:JSpecifyMode", "true")
}
// Include to disable NullAway on test code
if (name.toLowerCase().contains("test")) {
options.errorprone {
disable("NullAway")
}
}
}
generateGrammarSource {
includes = ['Graphql.g4']
maxHeapSize = "64m"
arguments += ["-visitor"]
outputDirectory = file("${project.buildDir}/generated-src/antlr/main/graphql/parser/antlr")
}
generateGrammarSource.inputs
.dir('src/main/antlr')
.withPropertyName('sourceDir')
.withPathSensitivity(PathSensitivity.RELATIVE)
task sourcesJar(type: Jar) {
dependsOn classes
archiveClassifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
archiveClassifier = 'javadoc'
from javadoc.destinationDir
}
javadoc {
options.encoding = 'UTF-8'
}
// Removed deprecated archives configuration in favor of direct assemble dependencies
List<TestDescriptor> failedTests = []
Map<String, Integer> testsAndTime = [:]
Map<String, Integer> testClassesAndTime = [:]
int testCount = 0
long testTime = 0L
tasks.withType(Test) {
if (!name.startsWith('testng')) {
useJUnitPlatform()
}
maxHeapSize = "1g"
testLogging {
events "FAILED", "SKIPPED"
exceptionFormat = "FULL"
}
// Required for JMH ArchUnit tests
classpath += sourceSets.jmh.output
dependsOn "jmhClasses"
afterTest { TestDescriptor descriptor, TestResult result ->
testCount++
if (result.getFailedTestCount() > 0) {
failedTests.add(descriptor)
}
def ms = (int) (result.endTime - result.startTime)
testTime += ms
String className = descriptor.className ?: "unknown"
String name = className + "." + descriptor.displayName
if (ms > 500) {
testsAndTime[name] = ms
testClassesAndTime.compute(className) { k, v -> v == null ? ms : v + ms }
println "\tTest '$name' took ${ms}ms"
}
}
}
tasks.register('testWithJava21', Test) {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(21)
}
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
classpath += sourceSets.jmh.output
dependsOn "jmhClasses"
dependsOn tasks.named('testClasses')
}
tasks.register('testWithJava17', Test) {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(17)
}
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
classpath += sourceSets.jmh.output
dependsOn "jmhClasses"
dependsOn tasks.named('testClasses')
}
tasks.register('testWithJava11', Test) {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(11)
}
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
dependsOn tasks.named('testClasses')
classpath += sourceSets.jmh.output
dependsOn "jmhClasses"
}
['11', '17', '21'].each { ver ->
tasks.register("testngWithJava${ver}", Test) {
useTestNG()
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(ver)
}
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
dependsOn tasks.named('testClasses')
}
}
test.dependsOn testWithJava21
test.dependsOn testWithJava17
test.dependsOn testWithJava11
jacoco {
toolVersion = "0.8.12"
}
jacocoTestReport {
dependsOn test
reports {
xml.required = true
html.required = true
csv.required = false
}
// Exclude generated ANTLR code from coverage
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: [
'graphql/parser/antlr/**',
'graphql/com/google/**',
'graphql/org/antlr/**'
])
}))
}
}
/*
* The gradle.buildFinished callback is deprecated BUT there does not seem to be a decent alternative in gradle 7
* So progress over perfection here
*
* See https://github.com/gradle/gradle/issues/20151
*/
gradle.buildFinished {
println "\n\n"
println "============================"
println "$testCount tests run in $testTime ms"
println "============================"
if (!failedTests.isEmpty()) {
println "\n\n"
println "============================"
println "These are the test failures"
println "============================"
for (td in failedTests) {
println "${td.getClassName()}.${td.getDisplayName()}"
}
println "============================"
}
// slowest tests
println "\n\n"
println "============================"
println "Top 20 slowest test classes"
println "============================"
showTestResults(testClassesAndTime,20) { e ->
println "\tTest class ${e.key} took ${e.value}ms"
}
println "\n\n"
println "============================"
println "Top 50 slowest tests"
println "============================"
showTestResults(testsAndTime,50) { e ->
println "\tTest ${e.key} took ${e.value}ms"
}
}
static private showTestResults(Map<String, Integer> testMap, int limit, Closure closure) {
testMap.entrySet().stream()
.sorted { e1, e2 -> e2.getValue() - e1.getValue() }
.limit(limit)
.forEach(closure)
}
allprojects {
tasks.withType(Javadoc) {
exclude('**/antlr/**')
}
}
publishing {
publications {
graphqlJava(MavenPublication) {
version = version
from components.java
artifact sourcesJar {
archiveClassifier = "sources"
}
artifact javadocJar {
archiveClassifier = "javadoc"
}
pom.withXml {
// Removing antlr4 below (introduced in `1ac98bf`) addresses an issue with
// the Gradle ANTLR plugin. `1ac98bf` can be reverted and this comment removed once
// that issue is fixed and Gradle upgraded. See https://goo.gl/L92KiF and https://goo.gl/FY0PVR.
//
// Removing antlr4-runtime and guava because the classes we want to use are "shaded" into the jar itself
// via the shadowJar task
def pomNode = asNode()
pomNode.dependencies.'*'.findAll() {
it.artifactId.text() == 'antlr4' || it.artifactId.text() == 'antlr4-runtime' || it.artifactId.text() == 'guava'
}.each() {
it.parent().remove(it)
}
pomNode.children().last() + {
resolveStrategy = Closure.DELEGATE_FIRST
name 'graphql-java'
description 'GraphqL Java'
url "https://github.com/graphql-java/graphql-java"
scm {
url "https://github.com/graphql-java/graphql-java"
connection "https://github.com/graphql-java/graphql-java"
developerConnection "https://github.com/graphql-java/graphql-java"
}
licenses {
license {
name 'MIT'
url 'https://github.com/graphql-java/graphql-java/blob/master/LICENSE.md'
distribution 'repo'
}
}
developers {
developer {
id 'andimarek'
name 'Andreas Marek'
}
}
}
}
}
}
}
nexusPublishing {
repositories {
sonatype {
username = System.env.MAVEN_CENTRAL_USER_NEW
password = System.env.MAVEN_CENTRAL_PASSWORD_NEW
// https://central.sonatype.org/publish/publish-portal-ossrh-staging-api/#configuration
nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/"))
// GraphQL Java does not publish snapshots, but adding this URL for completeness
snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/"))
}
}
}
signing {
setRequired { !project.hasProperty('publishToMavenLocal') }
def signingKey = System.env.MAVEN_CENTRAL_PGP_KEY
useInMemoryPgpKeys(signingKey, "")
sign publishing.publications
}
// all publish tasks depend on the build task
tasks.withType(PublishToMavenRepository) {
dependsOn build
}
// Only publish Maven POM, disable default Gradle modules file
tasks.withType(GenerateModuleMetadata) {
enabled = false
}