-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathjava_no_deps.gradle
More file actions
357 lines (316 loc) · 13.3 KB
/
java_no_deps.gradle
File metadata and controls
357 lines (316 loc) · 13.3 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
import org.gradle.jvm.toolchain.internal.SpecificInstallationToolchainSpec
apply plugin: 'java-library'
apply from: "$rootDir/gradle/codenarc.gradle"
apply from: "$rootDir/gradle/forbiddenapis.gradle"
apply from: "$rootDir/gradle/spotless.gradle"
apply from: "$rootDir/gradle/spotbugs.gradle"
apply from: "$rootDir/gradle/repositories.gradle"
apply from: "$rootDir/gradle/pitest.gradle"
apply from: "$rootDir/gradle/test-suites.gradle"
// Only run one testcontainers test at a time
ext.testcontainersLimit = gradle.sharedServices.registerIfAbsent("testcontainersLimit", BuildService) {
maxParallelUsages = 1
}
// Task for tests that want to run forked in their own separate JVM
if (tasks.matching({it.name == 'forkedTest'}).empty) {
tasks.register('forkedTest', Test).configure {
useJUnitPlatform()
}
}
def applyCodeCoverage = !(
project.path.startsWith(":dd-smoke-tests") ||
project.path == ":dd-java-agent" ||
project.path == ":dd-java-agent:load-generator" ||
project.path.startsWith(":dd-java-agent:benchmark") ||
project.path.startsWith(":dd-java-agent:instrumentation") ||
project.path.startsWith(":dd-java-agent:appsec:weblog:"))
if (applyCodeCoverage) {
apply from: "$rootDir/gradle/jacoco.gradle"
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
// when building with Java 9+, lazily set compiler --release flag to match target
def skipSettingCompilerRelease = project.findProperty('skipSettingCompilerRelease')
if (!skipSettingCompilerRelease && JavaVersion.current().isJava9Compatible()) {
compileJava.options.release = project.provider {
JavaVersion.toVersion(targetCompatibility).majorVersion as Integer
}
}
if (project.hasProperty('minJavaVersionForTests') && project.getProperty('minJavaVersionForTests') != JavaVersion.VERSION_1_7) {
def version = JavaVersion.toVersion(project.getProperty('minJavaVersionForTests'))
def name = "java$version.majorVersion"
sourceSets {
"main_$name" {
java.srcDirs "${project.projectDir}/src/main/$name"
}
}
"compileMain_${name}Java" {
sourceCompatibility = version
targetCompatibility = version
}
// "socket-utils" is only set to compileOnly because the implementation dependency incorrectly adds Java17 classes to all jar prefixes.
// This causes the AgentJarIndex to search for other non-Java17 classes in the wrong prefix location and fail to resolve class names.
dependencies {
if ("${project.projectDir}".endsWith("socket-utils")) {
compileOnly files(project.sourceSets."main_$name".output)
} else {
compileOnly files(project.sourceSets."main_$name".compileClasspath)
implementation files(project.sourceSets."main_$name".output)
}
}
jar {
from sourceSets."main_$name".output
}
// In some cases we would like to avoid setting java version to `minJavaVersionForTests`.
// For example we would like to be able to run profiling tests with ZULU8, but we cannot run it with other JDK8 implementations at the moment
def skipSettingTestJavaVersion = project.hasProperty('skipSettingTestJavaVersion') && project.getProperty('skipSettingTestJavaVersion')
if (!skipSettingTestJavaVersion) {
tasks.withType(JavaCompile).configureEach {
if (it.name.toLowerCase().contains("test")) {
sourceCompatibility = version
targetCompatibility = version
}
}
}
}
java {
// See https://docs.gradle.org/current/userguide/upgrading_version_5.html, Automatic target JVM version
disableAutoTargetJvm()
withJavadocJar()
withSourcesJar()
}
jar {
/**
Make Jar build fail on duplicate files
By default Gradle Jar task can put multiple files with the same name
into a Jar. This may lead to confusion. For example if auto-service
annotation processing creates files with same name in `scala` and
`java` directory this would result in Jar having two files with the
same name in it. Which in turn would result in only one of those
files being actually considered when that Jar is used leading to very
confusing failures.
Instead we should 'fail early' and avoid building such Jars.
*/
duplicatesStrategy = 'fail'
manifest {
attributes(
"Implementation-Title": project.name,
"Implementation-Version": project.version,
"Implementation-Vendor": "Datadog",
"Implementation-URL": "https://github.com/datadog/dd-trace-java",
)
}
}
tasks.withType(Javadoc).configureEach {
options.encoding = "utf-8"
options.docEncoding = "utf-8"
options.charSet = "utf-8"
options.addStringOption('Xdoclint:none', '-quiet')
doFirst {
if (project.ext.has("apiLinks")) {
options.links(*project.apiLinks)
}
}
}
javadoc {
source = sourceSets.main.java.srcDirs
classpath = configurations.compileClasspath
options {
setMemberLevel JavadocMemberLevel.PUBLIC
setAuthor true
links "https://docs.oracle.com/javase/8/docs/api/"
source = 8
}
}
def currentJavaHomePath = getJavaHomePath(System.getProperty("java.home"))
project.afterEvaluate {
def testJvm = gradle.startParameter.projectProperties["testJvm"]
def javaTestLauncher = null as Provider<JavaLauncher>
if (testJvm) {
def matcher = testJvm =~ /([a-zA-Z]*)([0-9]+)/
if (!matcher.matches()) {
throw new GradleException("Unable to find launcher for Java '$testJvm'. It needs to match '([a-zA-Z]*)([0-9]+)'.")
}
def testJvmLanguageVersion = matcher.group(2) as Integer
def testJvmEnv = "JAVA_${testJvm}_HOME"
def testJvmHome = System.getenv(testJvmEnv)
if (!testJvmHome) {
throw new GradleException("Unable to find launcher for Java '$testJvm'. Have you set '$testJvmEnv'?")
}
def testJvmHomePath = getJavaHomePath(testJvmHome)
// Only change test JVM if it's not the one we are running the gradle build with
if (currentJavaHomePath != testJvmHomePath) {
def jvmSpec = new SpecificInstallationToolchainSpec(project.getObjects(), file(testJvmHomePath))
// The provider always says that a value is present so we need to wrap it for proper error messages
Provider<JavaLauncher> launcher = providers.provider {
try {
return javaToolchains.launcherFor(jvmSpec).get()
} catch (NoSuchElementException ignored) {
throw new GradleException("Unable to find launcher for Java $testJvm. Does '$testJvmHome' point to a JDK?")
}
}
javaTestLauncher = launcher
}
}
tasks.withType(Test).configureEach {
def allowReflectiveAccessToJdk = true
if (project.hasProperty('allowReflectiveAccessToJdk')) {
allowReflectiveAccessToJdk = project.getProperty('allowReflectiveAccessToJdk')
}
if (javaTestLauncher) {
def metadata = javaTestLauncher.get().metadata
def allowedOrForced = !isJdkExcluded(testJvm) &&
(isJavaLanguageVersionAllowed(metadata.languageVersion, it.name) || isJdkForced(testJvm))
javaLauncher = javaTestLauncher
onlyIf { allowedOrForced }
if (applyCodeCoverage) {
jacoco {
// Disable jacoco for additional JVM tests to speed things up a bit
enabled = false
}
}
if (metadata.languageVersion.asInt() >= 16 && allowReflectiveAccessToJdk) {
// temporary workaround when using Java16+: some tests require reflective access to java.lang/java.util
jvmArgs += ['--add-opens=java.base/java.lang=ALL-UNNAMED', '--add-opens=java.base/java.util=ALL-UNNAMED']
}
} else {
def name = it.name
onlyIf { isJavaVersionAllowed(JavaVersion.current(), name) }
if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_16) && allowReflectiveAccessToJdk) {
jvmArgs += ['--add-opens=java.base/java.lang=ALL-UNNAMED', '--add-opens=java.base/java.util=ALL-UNNAMED']
}
}
if (configurations.hasProperty("latestDepTestRuntimeClasspath")) {
doFirst {
def testArtifacts = configurations.testRuntimeClasspath.resolvedConfiguration.resolvedArtifacts
def latestTestArtifacts = configurations.latestDepTestRuntimeClasspath.resolvedConfiguration.resolvedArtifacts
assert testArtifacts != latestTestArtifacts: "latestDepTest dependencies are identical to test"
}
}
}
[JavaCompile, ScalaCompile, GroovyCompile].each { type ->
tasks.withType(type).configureEach {
if (options.fork) {
options.forkOptions.with {
memoryMaximumSize = "256M"
}
}
}
}
if (project.plugins.hasPlugin('kotlin')) {
['compileKotlin', 'compileTestKotlin'].each { type ->
tasks.named(type).configure {
kotlinDaemonJvmArguments = ["-Xmx256m", "-XX:+UseParallelGC"]
}
}
}
tasks.withType(JavaExec).configureEach {
if (!it.maxHeapSize) {
it.maxHeapSize('256M')
}
}
}
if (project.plugins.hasPlugin('com.gradleup.shadow')) {
// Remove the no-deps jar from the archives to prevent publication
configurations.archives.with {
artifacts.remove artifacts.find {
if (it.hasProperty("delegate")) {
it.delegate.archiveTask.is jar
} else {
it.archiveTask.is jar
}
}
}
artifacts {
archives shadowJar
}
}
if (project.hasProperty("removeJarVersionNumbers") && removeJarVersionNumbers) {
tasks.withType(AbstractArchiveTask).configureEach {
archiveVersion.convention(null)
archiveVersion.set(null)
}
}
ext.setJavaVersion = (it, javaVersionInteger) -> {
Provider<JavaCompiler> compiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(javaVersionInteger)
}
Provider<JavaLauncher> launcher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(javaVersionInteger)
}
try {
if (it instanceof JavaCompile) {
JavaCompile jc = (JavaCompile) it
jc.javaCompiler = compiler
if (javaVersionInteger == 8) {
jc.options.release = null
}
} else if (it instanceof GroovyCompile) {
GroovyCompile gc = (GroovyCompile) it
gc.javaLauncher = launcher
} else if (it instanceof ScalaCompile) {
ScalaCompile sc = (ScalaCompile) it
sc.javaLauncher = launcher
} else {
throw new GradleException("Unsupported compile type: ${it.getClass()}")
}
} catch (NoSuchElementException ignored) {
throw new GradleException("Unable to find compiler for Java $javaVersionInteger. Have you set JAVA_${javaVersionInteger}_HOME?")
}
} as Closure<Void>
ext.getJavaLauncherFor = (javaVersionInteger) -> {
def launcher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(javaVersionInteger)
}
if (!launcher.present) {
throw new GradleException("Unable to find launcher for Java $javaVersionInteger. Have you set JAVA_${javaVersionInteger}_HOME?")
}
return launcher
} as Closure<Provider<JavaLauncher>>
def isJavaVersionAllowedForProperty(JavaVersion version, String propertyPrefix = "") {
def minProp = propertyPrefix.isEmpty() ? 'minJavaVersionForTests' : "${propertyPrefix}MinJavaVersionForTests"
def maxProp = propertyPrefix.isEmpty() ? 'maxJavaVersionForTests' : "${propertyPrefix}MaxJavaVersionForTests"
def definedMin = project.hasProperty(minProp)
def definedMax = project.hasProperty(maxProp)
if (definedMin && project.getProperty(minProp).compareTo(version) > 0) {
logger.info("isJavaVersionAllowedForProperty is false b/o minProp=${minProp} is defined and greater than version=${version}")
return false
}
//default to the general min if defined and specific one is was not defined
if (!propertyPrefix.isEmpty() && !definedMin && project.hasProperty('minJavaVersionForTests') && project.getProperty('minJavaVersionForTests').compareTo(version) > 0) {
logger.info("isJavaVersionAllowedForProperty is false b/o minJavaVersionForTests=${project.getProperty('minJavaVersionForTests')} is defined and greater than version=${version}")
return false
}
if (definedMax && project.getProperty(maxProp).compareTo(version) < 0) {
logger.info("isJavaVersionAllowedForProperty is false b/o maxProp=${project.getProperty(maxProp)} is defined and lower than version=${version}")
return false
}
if (!propertyPrefix.isEmpty() && !definedMax && project.hasProperty('maxJavaVersionForTests') && project.getProperty('maxJavaVersionForTests').compareTo(version) < 0) {
logger.info("isJavaVersionAllowedForProperty is false b/o maxJavaVersionForTests=${project.getProperty('maxJavaVersionForTests')} is defined and lower than version=${version}")
return false
}
return true
}
def isJavaVersionAllowed(JavaVersion version, String testTaskName) {
return isJavaVersionAllowedForProperty(version, testTaskName)
}
def isJavaLanguageVersionAllowed(JavaLanguageVersion languageVersion, String testTaskName) {
def version = JavaVersion.toVersion(languageVersion.asInt())
return isJavaVersionAllowed(version, testTaskName)
}
def isJdkForced(String javaName) {
return (project.hasProperty('forceJdk') && project.getProperty('forceJdk').any { it.equalsIgnoreCase(javaName) })
}
def isJdkExcluded(String javaName) {
return (project.hasProperty('excludeJdk') && project.getProperty('excludeJdk').any { it.equalsIgnoreCase(javaName) })
}
def getJavaHomePath(String path) {
def javaHome = new File(path).toPath().toRealPath()
return javaHome.endsWith("jre") ? javaHome.parent : javaHome
}
tasks.register('testJar', Jar) {
dependsOn(testClasses)
from sourceSets.test.output
archiveClassifier = 'test'
}
apply from: "$rootDir/gradle/configure_tests.gradle"