-
Notifications
You must be signed in to change notification settings - Fork 982
Expand file tree
/
Copy pathjava-shade.gradle
More file actions
525 lines (460 loc) · 21 KB
/
java-shade.gradle
File metadata and controls
525 lines (460 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
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import proguard.gradle.ProGuardTask
import java.util.concurrent.atomic.AtomicInteger
buildscript {
repositories {
gradlePluginPortal()
google()
}
dependencies {
classpath "com.gradleup.shadow:com.gradleup.shadow.gradle.plugin:${managedVersions['com.gradleup.shadow:com.gradleup.shadow.gradle.plugin']}"
classpath "com.guardsquare:proguard-gradle:${managedVersions['com.guardsquare:proguard-gradle']}"
}
}
def globalShadowExclusions = []
if (rootProject.hasProperty('shadowExclusions')) {
def rawShadowExclusions = rootProject.findProperty("shadowExclusions")
if (!(rawShadowExclusions instanceof String)) {
throw new RuntimeException("Property 'shadowExclusions' must be a String but was: ${rawShadowExclusions.getClass().name}")
}
globalShadowExclusions = rawShadowExclusions.split(",")
}
subprojects {
ext {
shadowExclusions = globalShadowExclusions.collect()
}
}
def relocatedProjects = projectsWithFlags('java', 'relocate')
def numConfiguredRelocatedProjects = new AtomicInteger()
configure(relocatedProjects) {
// per-dependency shade configuration
// while shade per-project shades all dependencies, shade per-dependency allows for finer control
def shadeConfig = project.configurations.create("shade") {
canBeResolved = true
canBeConsumed = false
}
project.configurations.api.extendsFrom(shadeConfig)
// Generate the shaded JARs.
task shadedJar(
type: ShadowJar,
group: 'Build',
description: 'Builds the shaded main JAR.',
dependsOn: tasks.classes) {
def self = this
def delegate0 = delegate
project.afterEvaluate {
self.configureShadowTask(project, delegate0, true)
}
archiveClassifier.set('shaded')
// Exclude the legacy file listing.
exclude '/META-INF/INDEX.LIST'
// Exclude the class signature files.
exclude '/META-INF/*.SF'
exclude '/META-INF/*.DSA'
exclude '/META-INF/*.RSA'
// Exclude the files generated by Maven
exclude '/META-INF/maven/**'
// Exclude the module metadata that'll become invalid after relocation.
exclude '**/module-info.class'
// Exclude the MRJARs files that are not compatible with the target Java version.
exclude { details ->
def path = details.path // e.g., META-INF/versions/15/com/example/Foo.class
def matcher = path =~ /^META-INF\/versions\/(\d+)\/.*$/
if (matcher.matches()) {
def version = matcher[0][1].toInteger()
return version > project.ext.targetJavaVersion
}
return false
}
// Set the 'Automatic-Module-Name' property in MANIFEST.MF.
if (project.ext.automaticModuleName != null) {
doFirst {
manifest {
attributes('Automatic-Module-Name': project.ext.automaticModuleName.get())
}
}
}
}
tasks.assemble.dependsOn tasks.shadedJar
artifacts {
archives shadedJar
}
task shadedClasses(
type: Copy,
group: 'Build',
description: 'Extracts the shaded main JAR.',
dependsOn: tasks.shadedJar) {
from(zipTree(tasks.shadedJar.archiveFile.get().asFile))
from(sourceSets.main.output.classesDirs) {
// Add the JAR resources excluded in the 'shadedJar' task.
include '**/*.jar'
}
into "${project.buildDir}/classes/java/shaded-main"
}
task shadedTestJar(
type: ShadowJar,
group: 'Build',
description: 'Builds the shaded test JAR.',
dependsOn: tasks.testClasses) {
def self = this
def delegate0 = delegate
project.afterEvaluate {
self.configureShadowTask(project, delegate0, false)
}
archiveBaseName.set("test-${tasks.jar.archiveBaseName.get()}-shaded")
}
task copyShadedTestClasses(
type: Copy,
group: 'Build',
description: 'Extracts the shaded test JAR.',
dependsOn: tasks.shadedTestJar) {
from(zipTree(tasks.shadedTestJar.archiveFile.get().asFile))
from(sourceSets.test.output.classesDirs) {
// Add the JAR resources excluded in the 'shadedTestJar' task.
include '**/*.jar'
}
into "${project.buildDir}/classes/java/shaded-test"
}
}
// NB: Configure in a new closure so that all relocated projects have a 'shadedJar' task.
configure(relocatedProjects) {
if (project.hasFlags('trim')) {
// Task 'shadedJar' may produce a very large JAR. Rename it to '<artifact>-untrimmed-<version>-shaded.jar' and
// let the task 'trimShadedJar' produce the trimmed JAR from it.
tasks.shadedJar.archiveBaseName.set("${tasks.jar.archiveBaseName.get()}-untrimmed")
task trimShadedJar(
type: ProGuardTask,
group: 'Build',
description: 'Shrinks the shaded JAR by removing unused classes.') {
relocatedProjects.each {
dependsOn it.tasks.shadedJar.path
dependsOn it.tasks.shadedTestJar.path
}
def shadedFile = tasks.shadedJar.archiveFile.get().asFile
// Rename the output file to '<artifact>-<version>-shaded.jar' by removing '-untrimmed' from
// the input file name.
def shadedAndTrimmedFile = file(shadedFile.path.replaceFirst('-untrimmed-', '-'))
injars shadedFile
// NB: By specifying 'outjars' *before* other 'injars' below, ProGuard will put only the classes
// from 'shadedFile' into 'shadedAndTrimmedFile'. See 'restructuring the output archives'
// for more information: https://www.guardsquare.com/en/proguard/manual/examples#restructuring
outjars shadedAndTrimmedFile
// Include all other shaded JARs so that ProGuard does not trim the classes and methods
// that are used actually.
injars tasks.shadedTestJar.archiveFile.get().asFile
relocatedProjects.each {
if (it != project && !it.hasFlags('no_aggregation')) {
injars it.tasks.shadedJar.archiveFile.get().asFile
injars it.tasks.shadedTestJar.archiveFile.get().asFile
}
}
def proguardLibraryConfigs = []
relocatedProjects.each { p ->
if (!p.hasFlags('no_aggregation')) {
configure(p) {
configurations {
proguardLibraryJarsElements {
canBeConsumed = true
canBeResolved = false
extendsFrom configurations.dependencyManagement
extendsFrom configurations.runtimeClasspath
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage, Usage.JAVA_RUNTIME))
}
}
}
}
def configName = "proguardLibraryJars_${p.path.replace(':', '_')}"
def proguardLibraryJars = configurations.create(configName) {
canBeConsumed = false
canBeResolved = true
// add attributes to match producer if you set any
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage, Usage.JAVA_RUNTIME))
}
}
proguardLibraryConfigs.add(proguardLibraryJars)
dependencies {
add(proguardLibraryJars.getName(), project(path: p.path, configuration: 'proguardLibraryJarsElements'))
}
}
}
// Filtering the libraryjars needs to be deferred to ensure all configurations are fully populated.
doFirst {
def dependencyJars = new LinkedHashSet<File>()
proguardLibraryConfigs.each { config ->
config.each { File file ->
if (!file.path.startsWith("${rootProject.projectDir}")) {
dependencyJars.add(file)
}
}
}
libraryjars files(dependencyJars)
}
// Add JDK. Use modules instead of rt.jar if possible.
def javaToolchainService = project.extensions.getByType(JavaToolchainService)
def javaPluginExt = project.extensions.getByType(JavaPluginExtension)
def launcher = javaToolchainService.launcherFor(javaPluginExt.toolchain).get()
File jdkHome = launcher.metadata.installationPath.asFile
File jmodDir = new File(jdkHome, "jmods")
if (jmodDir.isDirectory()) {
jmodDir.listFiles().findAll { File f ->
f.isFile() && f.name.toLowerCase(Locale.ENGLISH).endsWith(".jmod")
}.sort().each { libraryjars it }
} else {
File rtJar = new File(jdkHome, "jre/lib/rt.jar")
libraryjars rtJar
}
dontoptimize
dontobfuscate
dontwarn // Ignore the harmless 'missing classes' warnings related with the optional dependencies.
keepattributes '**'
keepparameternames
printconfiguration file("${project.buildDir}/proguard.cfg")
}
tasks.shadedClasses.dependsOn tasks.trimShadedJar
tasks.assemble.dependsOn tasks.trimShadedJar
// Add the trimmed JAR to archives.
artifacts {
trimShadedJar.outJarFiles.each {
archives it
}
}
}
}
// NB: Configure in a new closure so that all relocated projects have a 'shadedJar' or 'trimShadedJar' task.
configure(relocatedProjects) {
// Make sure the main classes are ready as well when `copyShadedTestClasses` is run,
// so that the tasks that require `copyShadedTestClasses` have everything required to run shaded tests.
tasks.copyShadedTestClasses.configure {
relocatedProjects.each {
if (it.tasks.findByName('trimShadedJar')) {
dependsOn it.tasks.trimShadedJar.path
} else {
dependsOn it.tasks.shadedJar.path
}
}
}
// Add tests for the shaded JAR.
testing.suites {
shadedTest(JvmTestSuite) {
targets.configureEach {
testTask.configure {
group = 'Verification'
description = 'Runs the unit tests with the shaded classes.'
project.ext.configureCommonTestSettings(it)
dependsOn tasks.copyShadedTestClasses
// The tests against the shaded artifacts should run after the tests against the unshaded ones.
shouldRunAfter tasks.test
testClassesDirs = files(tasks.copyShadedTestClasses.destinationDir)
classpath = testClassesDirs
project.ext.relocations.each {
exclude "${it['to'].replace('.', '/')}/**"
}
}
}
}
}
tasks.check.dependsOn testing.suites.shadedTest
// Configurations shouldn't be created in afterEvaluate so create it eagerly here before configuring it.
// In Gradle 8, dependencies can't be declared in a resolvable (canBeResolved=true) configuration. As a
// workaround two configurations are created to separate the declaration and resolving roles.
// - Directly declares dependencies to `shadedJarTestImplementation`.
// - Indirectly resolves the dependencies of `shadedJarTestImplementation` by creating a new configuration
// and extends `shadedJarTestImplementation`.
// https://discuss.gradle.org/t/problem-with-compileclasspath-after-gradle-8-update/44940
project.configurations.create("shadedJarTestImplementation") {
canBeResolved = false
canBeConsumed = false
}
project.configurations.create("shadedJarTestRuntime") {
canBeResolved = true
canBeConsumed = false
extendsFrom(project.configurations.shadedJarTestImplementation)
extendsFrom(project.configurations.dependencyManagement)
}
// Update the classpath of the 'shadedTest' task after all shaded projects are evaluated
// so that we get the complete dependency list.
project.afterEvaluate {
if (numConfiguredRelocatedProjects.incrementAndGet() == relocatedProjects.size()) {
relocatedProjects.each { p ->
configureShadedTestImplementConfiguration(p)
}
relocatedProjects.each { p ->
p.testing.suites.shadedTest.targets.configureEach {
testTask.configure {
classpath += p.configurations.getByName('shadedJarTestRuntime')
}
}
}
}
}
gradle.taskGraph.whenReady {
// Skip unshaded tests if shaded tests will run.
// To enable, set the property 'preferShadedTests' to 'false'.
boolean runUnshadedTests = false
if (rootProject.hasProperty('preferShadedTests') && "false" == rootProject.property('preferShadedTests')) {
runUnshadedTests = true
}
if (gradle.taskGraph.hasTask(tasks.shadedTest)) {
tasks.test.onlyIf { runUnshadedTests }
}
}
}
private void configureShadowTask(Project project, ShadowJar task, boolean isMain) {
List<Map<String, String>> relocations = project.ext.relocations
task.configure {
from(project.sourceSets[isMain ? 'main' : 'test'].output) {
exclude 'META-INF/maven/**'
// Prevent the shadow plugin from exploding the JARs in the resources directory.
// e.g. WEB-INF/lib/hello.jar
exclude '**/*.jar'
}
project.ext.shadowExclusions.each {
exclude it
}
configurations = [project.configurations[isMain ? 'compileClasspath' : 'testCompileClasspath']]
def shadeConfig = project.configurations.findByName("shade")
def shadedDeps = shadeConfig ?
shadeConfig.dependencies.collect { "${it.group}:${it.name}" }.toSet() :
[] as Set<String>
relocations.each { props ->
logger.debug("[${project.name}] Relocating ${props['name']} from ${props['from']} to ${props['to']} " +
"in ${isMain ? 'main' : 'test'}")
task.relocate(props['from'], props['to']) {
exclude {
return isGenerated(project, it.path, isMain)
}
}
}
dependencies {
if (project.hasFlags('shade')) {
// Shade the relocated dependencies only.
exclude { dep ->
if (!relocations.find { dep.name.startsWith("${it['name']}:") }) {
// Do not shade the dependencies not listed in 'relocations'.
return true
}
if (isMain) {
return false
} else {
// Do not shade the dependencies which is already shaded for 'main'.
return project.configurations.compileClasspath.allDependencies.any { compileDep ->
compileDep.group == dep.moduleGroup && compileDep.name == dep.moduleName
}
}
}
} else { // hasFlags('relocate')
// Only want to shade if explicitly specified on the dependency
exclude {
return !shadedDeps.contains("${it.moduleGroup}:${it.moduleName}")
}
}
}
}
}
boolean isGenerated(Project project, String path, boolean isMain) {
if (path.endsWith("package-info.class")) {
return false
}
if (!path.endsWith('.class')) {
return false
}
// Remove the .class extension.
def className = path.substring(0, path.length() - 6)
// Remove the inner class part.
def topLevelClassName = className.split('\\$')[0]
def javaSourcePath = "${topLevelClassName}.java"
def scope = isMain ? 'main' : 'test'
def thriftGenSrcDir = "${project.ext.genSrcDir}/${scope}/javaThrift"
def grpcGenSrcDir = "${project.buildDir}/generated/sources/proto/${scope}/grpc"
def protoGenSrcDir = "${project.buildDir}/generated/sources/proto/${scope}/java"
// Check if the source file exists in any of the generated source directories.
if (new File("${thriftGenSrcDir}/${javaSourcePath}").exists() ||
new File("${grpcGenSrcDir}/${javaSourcePath}").exists() ||
new File("${protoGenSrcDir}/${javaSourcePath}").exists()) {
logger.debug("[${project.name}] Excluding generated class from shading: ${path}")
return true
}
return false
}
/**
* Finds the dependencies of {@code project} recursively and adds the found dependencies to
* the configuration named as {@code 'shadedJarTestImplementation'}.
*/
private Configuration configureShadedTestImplementConfiguration(
Project project, Project recursedProject = project,
Set<ExcludeRule> excludeRules = new HashSet<>(),
Set<Project> visitedProjects = new HashSet<>(),
boolean recursedProjectRelocated = true) {
def shadedJarTestImplementation = project.configurations.getByName('shadedJarTestImplementation')
if (visitedProjects.contains(recursedProject)) {
return shadedJarTestImplementation
} else {
visitedProjects.add(recursedProject);
}
if (recursedProject.tasks.findByName('trimShadedJar')) {
project.dependencies.add(shadedJarTestImplementation.name, files(recursedProject.tasks.trimShadedJar.outJarFiles))
} else if (recursedProject.tasks.findByName('shadedJar')) {
project.dependencies.add(shadedJarTestImplementation.name, files(recursedProject.tasks.shadedJar.archiveFile.get().asFile))
}
def shadedDependencyNames = project.ext.relocations.collect { it['name'] }
def targetConfigurationName
if (project == recursedProject) {
targetConfigurationName = 'testRuntimeClasspath'
} else {
targetConfigurationName = 'runtimeClasspath'
}
def projectDependencies = []
recursedProject.configurations.findAll { cfg ->
cfg.name == targetConfigurationName
}.each { cfg ->
cfg.allDependencies.each { dep ->
if (dep instanceof ProjectDependency) {
if (!rootProject.findProject(dep.path).ext.hasFlag('java')) {
// Do not add the dependencies of non-Java projects.
return
}
// Project dependency - recurse later.
// Note that we recurse later to have immediate module dependencies higher precedence.
projectDependencies.add(dep)
} else {
// Module dependency - add.
if (shadedDependencyNames.contains("${dep.group}:${dep.name}")) {
if (recursedProjectRelocated) {
// Skip the shaded dependencies.
return
}
throw new IllegalStateException(
"${recursedProject} has a shaded dependency: ${dep.group}:${dep.name} " +
"but it is not relocated. Please add a 'relocate' flag to " +
"${recursedProject} in settings.gradle.")
}
if (excludeRules.find { rule ->
return rule.group == dep.group && rule.module == dep.name
}) {
// Skip the excluded dependencies.
return
}
// Do not use `project.dependencies.add(name, dep)` that discards the classifier of
// a dependency. See https://github.com/gradle/gradle/issues/23096
shadedJarTestImplementation.dependencies.add(dep)
}
}
}
// Recurse into the project dependencies.
projectDependencies.each { ProjectDependency dep ->
def dependencyProject = rootProject.findProject(dep.path)
if (!dependencyProject.ext.hasFlag('relocate')) {
shadedJarTestImplementation.dependencies.add(
project.dependencies.project(path: dep.dependencyProject.path))
recursedProjectRelocated = false
} else {
recursedProjectRelocated = true
}
configureShadedTestImplementConfiguration(
project, dependencyProject,
excludeRules + dep.excludeRules, visitedProjects, recursedProjectRelocated)
}
return shadedJarTestImplementation
}