-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
executable file
·772 lines (671 loc) · 24.1 KB
/
Copy pathbuild.gradle.kts
File metadata and controls
executable file
·772 lines (671 loc) · 24.1 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
/*
* This file is part of AndroidIDE.
*
* AndroidIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
*/
@file:Suppress("UnstableApiUsage")
import com.diffplug.spotless.LineEnding
import com.diffplug.spotless.extra.wtp.EclipseWtpFormatterStep
import com.itsaky.androidide.build.config.BuildConfig
import com.itsaky.androidide.build.config.FDroidConfig
import com.itsaky.androidide.build.config.publishingVersion
import com.itsaky.androidide.plugins.AndroidIDEPlugin
import com.itsaky.androidide.plugins.conf.configureAndroidModule
import com.itsaky.androidide.plugins.conf.configureJavaModule
import com.itsaky.androidide.plugins.conf.configureMavenPublish
import org.gradle.api.logging.Logger
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.time.Duration
import java.util.zip.CRC32
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
plugins {
id("build-logic.root-project")
alias(libs.plugins.android.application) apply false
alias(libs.plugins.android.library) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.jvm) apply false
alias(libs.plugins.maven.publish) apply false
alias(libs.plugins.gradle.publish) apply false
alias(libs.plugins.rikka.autoresconfig) apply false
alias(libs.plugins.rikka.materialthemebuilder) apply false
alias(libs.plugins.rikka.refine) apply false
alias(libs.plugins.google.protobuf) apply false
alias(libs.plugins.spotless)
alias(libs.plugins.sonarqube)
id("jacoco")
}
jacoco {
toolVersion = "0.8.11"
}
buildscript {
dependencies {
classpath(libs.kotlin.gradle.plugin)
classpath(libs.nav.safe.args.gradle.plugin)
}
}
// `jacocoAggregateReport` dependsOn every subproject's `testV8DebugUnitTest` and `sonarqube`
// dependsOn that, so a hard test failure skips both - even under `--continue` - and the analysis
// run uploads an empty coverage artifact with no Sonar analysis at all. That, not any individual
// module's broken suite, is the only reason `ignoreFailures` exists here: keep test failures
// non-fatal when the analysis chain is what was asked for, and let every ordinary build gate on them.
val analysisRun =
gradle.startParameter.taskNames.any {
it.substringAfterLast(':') in setOf("sonar", "sonarqube", "jacocoAggregateReport")
}
subprojects {
plugins.apply("jacoco")
extensions.configure<JacocoPluginExtension> {
toolVersion = "0.8.11"
}
// Always load the F-Droid config
FDroidConfig.load(project)
tasks.withType<Test> {
ignoreFailures = analysisRun
// Gradle's default test-worker heap is 512m, too small for the Robolectric +
// Kotlin Analysis API suites (:lsp:kotlin peaks near 240m and keeps growing).
// Keep it explicit so the suites fail on a real regression, not on the default.
maxHeapSize = "1g"
// Backstop: kill any individual Test task that runs longer than 10 minutes.
// Prevents a single hung test JVM (e.g. the Tooling API child) from burning
// the entire CI job budget.
timeout.set(Duration.ofMinutes(10))
// A test worker's default working dir is the module directory, so an unpathed
// -XX:+HeapDumpOnOutOfMemoryError drops a heap dump of up to maxHeapSize into the source
// tree, untracked and not gitignored. Keep dumps under build/ instead, one per task.
val heapDumpFile =
layout.buildDirectory
.file("test-heapdumps/$name.hprof")
.get()
.asFile
doFirst { heapDumpFile.parentFile.mkdirs() }
// JPMS opens required by the unit-test stack on JDK 17+:
// - jdk.unsupported/sun.misc: HiddenApiBypass.<clinit> reflectively
// resolves sun.misc.Unsafe; without this the IDEApplication
// static initializer fails and poisons every Robolectric test.
// - java.base/java.lang(.reflect): Mockito's field injector calls
// setAccessible on java.lang.Class fields.
// - java.base/java.io, java.util: needed by Robolectric/Gradle worker
// reflection in the same test JVM.
// - java.base/java.util.concurrent: the embedded IntelliJ scheduler
// reflectively reads FutureTask.callable; without this its periodic
// thread dies, disabling the cancellation poll that makes the Kotlin
// Analysis API interruptible mid-`analyze`.
jvmArgs(
"--add-opens=java.base/java.lang=ALL-UNNAMED",
"--add-opens=java.base/java.lang.reflect=ALL-UNNAMED",
"--add-opens=java.base/java.io=ALL-UNNAMED",
"--add-opens=java.base/java.util=ALL-UNNAMED",
"--add-opens=java.base/java.util.concurrent=ALL-UNNAMED",
"--add-opens=jdk.unsupported/sun.misc=ALL-UNNAMED",
// An OutOfMemoryError inside a test deadlocks Gradle's TestWorker: the
// OOM unwinds the runQueue.take() loop, whose finally needs the TestWorker
// monitor that the in-flight stop() already holds while blocked on
// runQueue.put() (capacity 1). The worker then never exits and the build
// hangs. Exiting on the first OOM turns that hang into a task failure.
"-XX:+ExitOnOutOfMemoryError",
"-XX:+HeapDumpOnOutOfMemoryError",
"-XX:HeapDumpPath=${heapDumpFile.absolutePath}",
)
// Attach jacoco agent
extensions.configure<JacocoTaskExtension> {
isIncludeNoLocationClasses = true
excludes = listOf("jdk.internal.*")
}
}
afterEvaluate {
apply {
plugin(AndroidIDEPlugin::class.java)
}
}
}
spotless {
ratchetFrom = "origin/stage"
// Common directories to exclude
// These mainly contain module that are external and huge, but are built from source
val commonTargetExcludes =
arrayOf(
"composite-builds/build-deps/java-compiler/**/*",
"composite-builds/build-deps/jaxp/**/*",
"composite-builds/build-deps/jdk-compiler/**/*",
"composite-builds/build-deps/jdk-jdeps/**/*",
"composite-builds/build-deps/jdt/**/*",
"composite-builds/build-login/properties-parser/**/*",
"eventbus/**/*",
"LayoutEditor/**/*",
"subprojects/aaptcompiler/src/*/java/com/android/**/*",
"subprojects/builder-model-impl/src/*/java/com/android/**/*",
"subprojects/flashbar/**/*",
"subprojects/xml-dom/**/*",
"termux/**/*",
)
// Dirs to PRUNE during the walk. Passing a fileTree to target() bypasses
// Spotless's auto-prune of .git/.gradle/build, so restore them. flox is the
// ADFA-4816 fix: its /nix/store symlinks (millions of files) made
// spotlessCheck take 12+ minutes.
// The pattern must match the directory node itself, because Gradle prunes a subtree only then;
// `dir/**` matches the contents instead and forces a descend-and-filter. Bare names are
// root-anchored: "flox" prunes only rootDir/flox, so anything that has to match at depth needs
// the `**/` prefix the three entries below carry. Dropping it -- reading "**/.gradle" as
// equivalent to ".gradle" -- would stop pruning every per-project cache dir and bring back the
// ADFA-4816 12-minute spotlessCheck.
val traversalExcludes =
arrayOf(
"flox",
"**/.flox",
"**/.git",
"**/.gradle",
)
// Gradle build-output dirs (root + subprojects), relative to rootDir. Not
// "**/build": source packages named `build` exist (e.g.
// app/src/main/java/.../actions/build) and would be dropped.
val buildOutputExcludes =
allprojects
.map {
it.layout.buildDirectory
.get()
.asFile
.relativeTo(rootDir)
.invariantSeparatorsPath
}.filter { it.isNotEmpty() && !it.startsWith("..") }
.toTypedArray()
// Target tree with the shared excludes applied; format-specific ones go in
// extraExcludes.
fun spotlessTarget(
vararg includes: String,
extraExcludes: Array<String> = emptyArray(),
) = fileTree(rootDir) {
include(*includes)
exclude(*commonTargetExcludes)
exclude(*traversalExcludes)
exclude(*buildOutputExcludes)
exclude(*extraExcludes)
}
// ALWAYS use line feeds (LF -- '\n')
lineEndings = LineEnding.UNIX
java {
eclipse()
.configFile("spotless.eclipse-java.xml")
// Sort member variables in the following order
// SF,SI,SM,F,I,C,M,T = Static Fields, Static Initializers, Static Methods, Fields, Initializers, Constructors, Methods, (Nested) Types
.sortMembersEnabled(true)
.sortMembersOrder("SF,SI,SM,F,I,C,M,T")
// Disable field sorting
// some fields reference other fields of the same class, which can cause compilation
// errors if re-ordered
.sortMembersDoNotSortFields(true)
// Sort members based on their visibility in the following order
// B,R,D,V = Public, Protected, Package, Private
.sortMembersVisibilityOrderEnabled(true)
.sortMembersVisibilityOrder("B,R,D,V")
// use tabs
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
// enable import ordering
importOrder()
removeUnusedImports()
forbidWildcardImports()
// Fix lambda formatting. Built-in replace() steps are equality-stable, so
// spotlessJava stays cacheable/up-to-date; a custom FormatterFunc is not and
// forces the Java format to re-run on every build.
replace("Lambda fix paren", "} )", "})")
replace("Lambda fix comma", "} ,", "},")
target(spotlessTarget("**/src/*/java/**/*.java"))
}
kotlin {
// compose-rules ruleset validates @Composable naming/conventions so we can enable
// PascalCase Composables (see ktlint_function_naming_ignore_when_annotated_with in .editorconfig)
val composeRulesKtlint =
libs.compose.rules.ktlint
.get()
ktlint().customRuleSets(listOf("${composeRulesKtlint.module}:${composeRulesKtlint.version}"))
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
target(
spotlessTarget(
"**/src/*/java/**/*.kt",
"**/src/*/kotlin/**/*.kt",
),
)
suppressLintsFor {
// suppress the 'file name <some-file> should conform PascalCase' errors
step = "ktlint"
shortCode = "standard:filename"
}
}
kotlinGradle {
ktlint()
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
target(spotlessTarget("**/*.gradle.kts"))
}
format("xml") {
eclipseWtp(EclipseWtpFormatterStep.XML)
.configFile("spotless.eclipse-xml.prefs")
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
// Eclipse WTP splits strings.xml entries across lines, so exclude it. LSP test
// fixtures (testing/resources/test-project/**/*_template.xml) embed an
// "@@cursor@@" marker inside attribute-like text; the formatter splits it
// across lines too, breaking the marker lookup, so exclude those as well.
target(
spotlessTarget(
"**/src/*/res/**/*.xml",
extraExcludes =
arrayOf(
"**/src/*/res/values*/strings.xml",
"testing/resources/test-project/**/*_template.xml",
),
),
)
}
format("misc") {
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
// Only .gitignore; `.gradle` is a cache dir, pruned via traversalExcludes.
target(spotlessTarget("**/.gitignore"))
}
shell {
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
target(
".githooks/**/*",
"scripts/**/*",
)
targetExclude("scripts/debug-keystore/adfa-keystore.jks")
}
}
allprojects {
project.group = BuildConfig.PACKAGE_NAME
project.version = rootProject.version
plugins.withId("com.android.application") {
configureAndroidModule(libs.androidx.libDesugaring)
}
plugins.withId("com.android.library") {
configureAndroidModule(libs.androidx.libDesugaring)
}
plugins.withId("java-library") {
configureJavaModule()
}
plugins.withId("com.vanniktech.maven.publish.base") {
configureMavenPublish()
}
plugins.withId("com.gradle.plugin-publish") {
configure<GradlePluginDevelopmentExtension> {
version = project.publishingVersion
}
}
tasks.withType<KotlinCompile>().configureEach {
compilerOptions.jvmTarget.set(JvmTarget.fromTarget(BuildConfig.JAVA_VERSION.majorVersion))
}
}
tasks.named<Delete>("clean") {
doLast {
delete(rootProject.layout.buildDirectory)
}
}
sonar {
properties {
val binaries =
subprojects.flatMap { subproj ->
val dirs =
listOf(
subproj.layout.buildDirectory
.dir("classes/java/main")
.get()
.asFile,
subproj.layout.buildDirectory
.dir("classes/kotlin/main")
.get()
.asFile,
subproj.layout.buildDirectory
.dir("intermediates/javac/v8Debug/classes")
.get()
.asFile,
subproj.layout.buildDirectory
.dir("tmp/kotlin-classes/v8Debug")
.get()
.asFile,
)
// include directories that actually exist
dirs.filter { it.exists() }.map { it.absolutePath }
}
property("sonar.java.binaries", binaries.joinToString(","))
property("sonar.c.file.suffixes", "-")
property("sonar.cpp.file.suffixes", "-")
property("sonar.objc.file.suffixes", "-")
property(
"sonar.coverage.jacoco.xmlReportPaths",
project.layout.buildDirectory
.dir("reports/jacoco/jacocoAggregateReport/jacocoAggregateReport.xml")
.get()
.asFile.absolutePath,
)
property("sonar.host.url", "https://sonarcloud.io")
property("sonar.projectKey", "appdevforall_CodeOnTheGo")
property("sonar.organization", "app-dev-for-all")
property("sonar.androidVariant", "v8Debug")
property("sonar.token", System.getenv("SONAR_TOKEN"))
// The Sonar Android sensor auto-scans every Android module for a
// lint XML at the standard AGP path and emits "Unable to import"
// for each module where lint never ran (~57 warnings, because the
// analyze workflow uses `-x lint`). Pin the property to a single
// empty-but-valid report so the sensor finds something and the
// auto-scan never runs. See :generateEmptySonarLintReport below.
property(
"sonar.androidLint.reportPaths",
project.layout.buildDirectory
.file("reports/sonar/empty-lint-report.xml")
.get()
.asFile.absolutePath,
)
}
}
val generateEmptySonarLintReport by tasks.registering {
val output = project.layout.buildDirectory.file("reports/sonar/empty-lint-report.xml")
outputs.file(output)
doLast {
val file = output.get().asFile
file.parentFile.mkdirs()
file.writeText(
"""<?xml version="1.0" encoding="UTF-8"?>
|<issues format="6" by="empty-placeholder"></issues>
|
""".trimMargin(),
)
}
}
tasks.named("sonarqube") {
dependsOn("jacocoAggregateReport", generateEmptySonarLintReport)
}
tasks.register<JacocoReport>("jacocoAggregateReport") {
val excludedProjects = emptySet<String>()
// (variant directory, unit-test task) pairs, v8 first so a flavored module keeps using it. Two
// entries because the module set is not uniform: every flavored module builds `v8Debug`, but a
// flavorless one such as `:plugin-api` only builds `debug`. Collecting the v8 names alone dropped
// such a module from this report silently - `mapNotNull` returned nothing for it, so its tests
// never ran here and its classes counted for nothing.
val coverageVariants =
listOf(
"v8Debug" to "testV8DebugUnitTest",
"debug" to "testDebugUnitTest",
)
// One unit-test task per subproject, not one per variant: a module has only ever one of these.
dependsOn(
subprojects
.filterNot { it.name in excludedProjects }
.mapNotNull { subproj ->
coverageVariants.firstNotNullOfOrNull { (_, task) -> subproj.tasks.findByName(task) }
},
)
reports {
xml.required.set(true)
html.required.set(true)
}
val fileFilter =
listOf(
"**/R.class",
"**/R$*.class",
"**/BuildConfig.*",
"**/Manifest*.*",
"**/*Test*.*",
)
// Kotlin and java class directories, for each variant a module might have built. Absent
// directories contribute nothing, so listing both shapes per module is safe.
val classDirs =
subprojects
.filterNot { it.name in excludedProjects }
.flatMap { subproj ->
coverageVariants.flatMap { (variant, _) ->
listOf(
fileTree(subproj.layout.buildDirectory.dir("tmp/kotlin-classes/$variant")) {
exclude(fileFilter)
},
fileTree(subproj.layout.buildDirectory.dir("tmp/kotlin-classes/${variant}UnitTest")) {
exclude(fileFilter)
},
fileTree(subproj.layout.buildDirectory.dir("classes/java/$variant")) {
exclude(fileFilter)
},
fileTree(subproj.layout.buildDirectory.dir("intermediates/javac/${variant}UnitTest/classes")) {
exclude(fileFilter)
},
)
}
}
// Untouched on purpose, though it names only `src/main/java` while nine modules keep sources under
// `src/main/kotlin`: this property is inert for this task. Emptying it outright still renders full
// Kotlin source in the HTML and leaves the XML byte-identical, so adding the Kotlin roots here
// buys nothing. Measured, not assumed - do not "fix" it without re-measuring.
val sourceDirs =
subprojects
.filterNot { it.name in excludedProjects }
.map { it.file("src/main/java") }
// Collect execution data (.exec files), for each variant a module might have run.
val execFiles =
subprojects
.filterNot { it.name in excludedProjects }
.flatMap { subproj ->
coverageVariants.map { (variant, task) ->
subproj.layout.buildDirectory.file(
"outputs/unit_test_code_coverage/${variant}UnitTest/$task.exec",
)
}
}
classDirectories.setFrom(classDirs)
sourceDirectories.setFrom(sourceDirs)
executionData.setFrom(execFiles)
}
val mavenCacheDirProvider = providers.gradleProperty("mavenCacheDir").orElse("build/maven-cache")
val localMavenRepoDirProvider = providers.gradleProperty("localMavenRepoDir").orElse("build/localMavenRepository")
val mavenRepoDirProvider = providers.gradleProperty("mavenRepoDir").orElse(localMavenRepoDirProvider)
val zeroMavenRepoDirProvider =
providers
.gradleProperty("zeroMavenRepoDir")
.orElse(
mavenRepoDirProvider.map { repoDir ->
val repoPath = file(repoDir).toPath()
val fileName = repoPath.fileName.toString()
repoPath.resolveSibling("$fileName-zero").toString()
},
)
tasks.register("cacheToLocalMavenRepo") {
group = "cicd"
description = "Converts an exported Gradle module cache into a local Maven repository layout."
val source = mavenCacheDirProvider.map { file(it) }
val destination = localMavenRepoDirProvider.map { file(it) }
inputs.dir(source)
outputs.dir(destination)
doLast {
convertCacheToLocalMavenRepo(source.get().toPath(), destination.get().toPath(), logger)
}
}
tasks.register("zeroCompressMavenRepo") {
group = "cicd"
description = "Copies a Maven repository and rewrites all JAR/AAR archives with ZIP zero compression."
val source = mavenRepoDirProvider.map { file(it) }
val destination = zeroMavenRepoDirProvider.map { file(it) }
val validateArchives =
providers
.gradleProperty("zeroMavenRepoValidate")
.map(String::toBoolean)
.orElse(true)
inputs.dir(source)
inputs.property("validateArchives", validateArchives)
outputs.dir(destination)
doLast {
zeroCompressMavenRepo(
source = source.get().toPath(),
destination = destination.get().toPath(),
validateArchives = validateArchives.get(),
logger = logger,
)
}
}
tasks.register("zeroCompressLocalMavenRepo") {
group = "cicd"
description = "Converts an exported Gradle cache to a local Maven repository, then zero-compresses all JAR/AAR archives."
dependsOn("cacheToLocalMavenRepo", "zeroCompressMavenRepo")
}
tasks.named("zeroCompressMavenRepo") {
mustRunAfter("cacheToLocalMavenRepo")
}
fun Path.resolveParts(parts: Iterable<String>): Path = parts.fold(this) { path, part -> path.resolve(part) }
fun Path.relativeTo(base: Path): Path = base.relativize(this)
fun Path.normalizedAbsolute(): Path = toAbsolutePath().normalize()
fun convertCacheToLocalMavenRepo(
source: Path,
destination: Path,
logger: Logger,
) {
val allowedExtensions = setOf("aar", "jar", "module", "pom")
val normalizedSource = source.normalizedAbsolute()
val normalizedDestination = destination.normalizedAbsolute()
require(Files.isDirectory(normalizedSource)) {
"Maven cache directory does not exist or is not a directory: $normalizedSource"
}
require(!normalizedDestination.startsWith(normalizedSource)) {
"Local Maven output directory must not be inside the input cache: $normalizedDestination"
}
Files.createDirectories(normalizedDestination)
normalizedSource
.toFile()
.walkTopDown()
.filter { it.isFile }
.filter { it.extension.lowercase() in allowedExtensions }
.forEach { file ->
val filePath = file.toPath()
val relativeParent =
filePath.parent
?.let { normalizedSource.relativize(it).map(Path::toString).toList() }
.orEmpty()
val targetParts =
if (relativeParent.firstOrNull()?.contains(".") == true) {
relativeParent.first().split(".") + relativeParent.drop(1).dropLast(1)
} else {
relativeParent.dropLast(1)
}
val targetParent = normalizedDestination.resolveParts(targetParts)
val targetFile = targetParent.resolve(file.name)
Files.createDirectories(targetParent)
Files.copy(filePath, targetFile, StandardCopyOption.REPLACE_EXISTING)
logger.lifecycle("Copied ${filePath.relativeTo(normalizedSource)} -> ${targetFile.relativeTo(normalizedDestination)}")
}
}
fun zeroCompressMavenRepo(
source: Path,
destination: Path,
validateArchives: Boolean,
logger: Logger,
) {
val normalizedSource = source.normalizedAbsolute()
val normalizedDestination = destination.normalizedAbsolute()
require(Files.isDirectory(normalizedSource)) {
"Maven repository directory does not exist or is not a directory: $normalizedSource"
}
require(!normalizedDestination.startsWith(normalizedSource)) {
"Zero-compressed output directory must not be inside the input repository: $normalizedDestination"
}
Files.createDirectories(normalizedDestination)
normalizedSource
.toFile()
.walkTopDown()
.filter { it.isFile }
.forEach { file ->
val sourceFile = file.toPath()
val targetFile = normalizedDestination.resolve(normalizedSource.relativize(sourceFile))
Files.createDirectories(targetFile.parent)
when (file.extension.lowercase()) {
"aar", "jar" -> {
zeroCompressArchive(sourceFile, targetFile)
if (validateArchives) {
validateZeroCompressedArchive(sourceFile, targetFile)
}
logger.lifecycle("Zero-compressed ${sourceFile.relativeTo(normalizedSource)}")
}
else -> {
Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING)
}
}
}
}
fun zeroCompressArchive(
source: Path,
destination: Path,
) {
ZipInputStream(Files.newInputStream(source).buffered()).use { input ->
ZipOutputStream(Files.newOutputStream(destination).buffered()).use { output ->
while (true) {
val entry = input.nextEntry ?: break
val bytes = if (entry.isDirectory) ByteArray(0) else input.readBytes()
val crc = CRC32().apply { update(bytes) }.value
val outputEntry =
ZipEntry(entry.name).apply {
comment = entry.comment
extra = entry.extra
method = ZipEntry.STORED
size = bytes.size.toLong()
compressedSize = bytes.size.toLong()
this.crc = crc
if (entry.time >= 0) {
time = entry.time
}
}
output.putNextEntry(outputEntry)
if (!entry.isDirectory) {
output.write(bytes)
}
output.closeEntry()
input.closeEntry()
}
}
}
}
fun validateZeroCompressedArchive(
source: Path,
destination: Path,
) {
ZipFile(source.toFile()).use { sourceZip ->
ZipFile(destination.toFile()).use { destinationZip ->
val sourceEntries =
sourceZip
.entries()
.asSequence()
.map { it.name }
.toSet()
val destinationEntries = destinationZip.entries().asSequence().toList()
val destinationEntryNames = destinationEntries.map { it.name }.toSet()
require(sourceEntries == destinationEntryNames) {
"Entry mismatch after zero-compressing $source"
}
val compressedEntry =
destinationEntries.firstOrNull { !it.isDirectory && it.method != ZipEntry.STORED }
require(compressedEntry == null) {
"Archive entry was not zero-compressed in $destination: ${compressedEntry?.name}"
}
}
}
}