-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
478 lines (428 loc) · 20.4 KB
/
Copy pathbuild.gradle.kts
File metadata and controls
478 lines (428 loc) · 20.4 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
@file:Suppress("UnstableApiUsage")
import com.android.build.gradle.AppExtension
import com.android.build.gradle.LibraryExtension
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import org.jetbrains.kotlin.gradle.targets.js.testing.KotlinJsTest
// Detect host architecture and OS
val osName = System.getProperty("os.name").lowercase()
val arch = System.getProperty("os.arch").lowercase()
// Only override Kotlin/Native home for Apple Silicon macOS
if (osName.contains("mac") && arch == "aarch64") {
val konanDir = File(System.getProperty("user.home"), ".konan")
val nativeDir = konanDir.listFiles()?.firstOrNull {
it.isDirectory && it.name.startsWith("kotlin-native-prebuilt-macos-aarch64")
}
if (nativeDir != null) {
logger.lifecycle("Using Kotlin/Native ARM64 toolchain at: ${nativeDir.absolutePath}")
project.extensions.extraProperties["kotlin.native.home"] = nativeDir.absolutePath
} else {
logger.warn("No ARM64 Kotlin/Native toolchain found in ~/.konan — defaulting to automatic download.")
}
} else {
logger.lifecycle("Using default Kotlin/Native toolchain for $osName ($arch)")
}
allprojects {
group = "com.sphereon.idk"
version = "0.25.0-SNAPSHOT"
val npmVersion by extra { getNpmVersion() }
// Workaround: Gradle's Kryo-based test output serializer corrupts binary result files when
// Kotlin/Native tests produce output with non-standard characters (hex addresses, mangled symbols).
// The allTests aggregate report task crashes reading these files. Individual test tasks (jvmTest,
// linuxX64Test, etc.) still detect and report failures correctly.
// See: https://github.com/gradle/gradle/issues/25268
tasks.withType<org.gradle.api.tasks.testing.TestReport>().configureEach {
if (name == "allTests") enabled = false
}
// Workaround: Kotlin 2.3.x npm-publish plugin registers wasmJs tasks whose mainFile provider
// has no value, causing assembleWasmJsPackage to fail during task graph construction.
// When wasmJs is NOT in kmp.targets, pre-register no-op tasks before the npm-publish plugin
// can create its broken versions. When wasmJs IS active, the ConventionsPlugin workaround handles it.
run {
val kmpTargets = (System.getProperty("kmp.targets") ?: "jvm").split(",").map { it.trim().lowercase() }
if ("all" !in kmpTargets && "wasmjs" !in kmpTargets && "wasm" !in kmpTargets) {
}
}
plugins.withType<MavenPublishPlugin> {
configure<PublishingExtension> {
repositories {
maven {
name = "sphereon-opensource"
val snapshotsUrl = "https://nexus.sphereon.com/repository/sphereon-opensource-snapshots/"
val releasesUrl = "https://nexus.sphereon.com/repository/sphereon-opensource-releases/"
url = uri(if (version.toString().contains("SNAPSHOT")) snapshotsUrl else releasesUrl)
credentials {
username = System.getenv("NEXUS_USERNAME")
password = System.getenv("NEXUS_PASSWORD")
}
}
}
}
}
}
plugins {
alias(sphereonplug.plugins.com.sphereon.gradle.plugin.conventions) apply false
alias(sphereonplug.plugins.com.sphereon.gradle.plugin.integration.tests) apply false
alias(sphereonplug.plugins.com.sphereon.gradle.plugin.project.publication) apply false
alias(sphereonplug.plugins.com.android.library) apply false
alias(sphereonplug.plugins.com.android.application) apply false
alias(sphereonplug.plugins.com.android.kotlin.multiplatform.library) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlin.multiplatform) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlin.jvm) apply false
alias(sphereonplug.plugins.com.vanniktech.maven.publish) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlin.plugin.serialization) apply false
alias(sphereonplug.plugins.io.kotest.io.kotest.gradle.plugin) apply false
alias(sphereonplug.plugins.com.google.devtools.ksp.com.google.devtools.ksp.gradle.plugin) apply false
alias(sphereonplug.plugins.dev.zacsweers.metro) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlin.android) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlin.npm.publish.org.jetbrains.kotlin.npm.publish.gradle.plugin) apply false
alias(sphereonplug.plugins.software.amazon.app.platform) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlinx.atomicfu) apply false
alias(sphereonplug.plugins.org.jetbrains.kotlin.plugin.compose) apply false
alias(sphereonplug.plugins.org.jetbrains.compose) apply false
alias(sphereonplug.plugins.org.jetbrains.compose.hot.reload) apply false
alias(sphereonplug.plugins.io.ktor.plugin) apply false
alias(sphereonplug.plugins.org.jlleitschuh.gradle.ktlint) apply false
alias(sphereonplug.plugins.io.gitlab.arturbosch.detekt) apply false
alias(sphereonplug.plugins.org.jetbrains.dokka)
}
subprojects {
// Modules excluded from ktlint (generated code that gets added to source sets)
val ktlintExcludedModules = setOf(
"lib-crypto-kms-rest-api", // OpenAPI generated sources
"lib-crypto-kms-provider-digidentity", // OpenAPI generated sources
"lib-crypto-key-persistence-sqlite", // SQLDelight generated sources in commonMain source set
"lib-crypto-kms-provider-aws", // BuildKonfig generated sources in commonMain source set
"lib-crypto-kms-provider-azure", // BuildKonfig generated sources in commonMain source set
"lib-data-store-okd-openapi", // OpenAPI generated sources
)
if (!name.endsWith("-bom")) {
apply(plugin = "com.sphereon.gradle.plugin.conventions")
if (name !in ktlintExcludedModules) {
apply(plugin = "org.jlleitschuh.gradle.ktlint")
apply(plugin = "io.gitlab.arturbosch.detekt")
}
}
plugins.withId("org.jlleitschuh.gradle.ktlint") {
configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
version.set("1.8.0")
outputToConsole.set(true)
coloredOutput.set(true)
filter {
exclude { element -> element.file.absolutePath.replace('\\', '/').contains("/build/") }
}
}
}
plugins.withId("io.gitlab.arturbosch.detekt") {
configure<io.gitlab.arturbosch.detekt.extensions.DetektExtension> {
config.setFrom(rootProject.files("config/detekt/detekt.yml"))
baseline = file("config/detekt/baseline.xml")
buildUponDefaultConfig = false
allRules = false
parallel = true
ignoreFailures = true
autoCorrect = false
}
tasks.matching { it.name == "detektGenerateConfig" }.configureEach {
enabled = false
}
}
// kotlinx-io uses eval('require')('os') internally, which fails in ESM mode because
// `require` is not available in ES modules. Provide require to ESM modules via a CJS preload shim.
// See: https://github.com/Kotlin/kotlinx-io/issues/345
val shimFile = rootProject.file("gradle-build-support/js/esm-require-shim.cjs")
if (shimFile.exists()) {
tasks.withType<KotlinJsTest>().configureEach {
nodeJsArgs.add("--require")
nodeJsArgs.add(shimFile.absolutePath)
}
}
// xmlutil 0.90.1: duplicate function declarations in JS ESM output. 0.91.3 fixes this.
// kotlinx-datetime: pin to the `0.7.1-0.6.x-compat` flavour. Vanilla
// 0.7.1 moved `kotlinx.datetime.Instant` into `kotlin.time` (typealias)
// and ships no class file on the runtime classpath. Kotlin Dataframe's
// CSV / convert bytecode still calls the old class and throws
// `NoClassDefFoundError: kotlinx/datetime/Instant` at ingest. The compat
// build keeps both the legacy class and the new stdlib alias, so both
// Dataframe and IDK call sites resolve. Force on every configuration so
// a transitive 0.7.1 request loses the conflict (Gradle's version
// ordering does NOT consider `0.7.1-0.6.x-compat` greater than `0.7.1`,
// so without an explicit force the non-compat variant wins).
configurations.configureEach {
resolutionStrategy {
force("io.github.pdvrieze.xmlutil:core:0.91.3")
force("io.github.pdvrieze.xmlutil:serialization:0.91.3")
force("org.jetbrains.kotlinx:kotlinx-datetime:0.7.1-0.6.x-compat")
// Kotlin RC: force all Kotlin artifacts to match compiler version across all targets
val kotlinVersion = extra["kotlin.version"] as String
force("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-test:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-test-common:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-test-junit5:$kotlinVersion")
force("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
}
}
plugins.withId("com.android.library") {
extensions.configure<LibraryExtension> {
defaultConfig {
minSdk = 27
}
}
}
plugins.withId("com.android.application") {
extensions.configure<AppExtension> {
defaultConfig {
minSdk = 27
}
}
}
}
repositories {
mavenCentral()
google()
gradlePluginPortal()
maven {
url = uri("https://oss.sonatype.org/content/repositories/snapshots/")
mavenContent { snapshotsOnly() }
}
maven {
url = uri("https://aws.oss.sonatype.org/content/repositories/snapshots/")
mavenContent { snapshotsOnly() }
content { includeGroupAndSubgroups("software.amazon") }
}
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") {
content {
includeGroupAndSubgroups("org.jetbrains.compose")
includeGroupAndSubgroups("org.jetbrains.kotlin")
includeGroupAndSubgroups("org.jetbrains.kotlinx")
includeGroupAndSubgroups("org.jetbrains.skiko")
}
}
// Keep maven local at the end!!!!
// https://slack-chats.kotlinlang.org/t/27045384/hi-there-i-have-a-very-annoying-internal-compiler-error-here
mavenLocal {
content {
includeGroupAndSubgroups("com.sphereon")
}
}
}
fun getNpmVersion(): String {
val baseVersion = project.version.toString()
if (!baseVersion.endsWith("-SNAPSHOT")) {
return baseVersion
}
// Get git commit hash (workingDir needed for composite builds)
val gitCommitHash = providers.exec {
workingDir = rootDir
commandLine("git", "rev-parse", "--short=7", "HEAD")
}.standardOutput.asText.get().replace("\n", "").trim()
// npm registry rejects republishing the same version, so each SNAPSHOT publish
// must produce a unique version. Add a monotonic build id (CI run number, or
// local UTC timestamp) so consecutive publishes always get a fresh version.
val buildId = System.getenv("GITHUB_RUN_NUMBER")
?: DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
.withZone(ZoneOffset.UTC)
.format(Instant.now())
val baseNoSuffix = baseVersion.removeSuffix("-SNAPSHOT")
return "$baseNoSuffix-SNAPSHOT.$buildId.$gitCommitHash"
}
// =============================================================================
// Aggregate Test Task for running all IDK tests from root
// =============================================================================
tasks.register("allTests") {
group = "verification"
description = "Run all IDK tests across all subprojects"
dependsOn(provider { subprojects.mapNotNull { it.tasks.findByName("allTests") } })
}
// =============================================================================
// Aggregate NPM Tasks for publishing JS packages
// =============================================================================
tasks.register("publishAllNpmPackages") {
group = "publishing"
description = "Publish all IDK npm packages to npmjs"
dependsOn(provider { subprojects.mapNotNull { it.tasks.findByName("publishJsPackageToNpmjsRegistry") } })
}
tasks.register("assembleAllNpmPackages") {
group = "publishing"
description = "Assemble all IDK npm packages (validate without publishing)"
dependsOn(provider { subprojects.mapNotNull { it.tasks.findByName("assembleJsPackage") } })
}
// Force evaluation of every subproject so the deprecation task below can
// inspect their applied plugins. Only runs when the task is actually requested.
if (gradle.startParameter.taskNames.any { it.endsWith("listNpmPackageNames") }) {
subprojects.forEach { evaluationDependsOn(it.path) }
}
tasks.register("listNpmPackageNames") {
group = "publishing"
description = "Write all @sphereon/idk-* npm package names this build publishes to build/npm-packages.txt"
notCompatibleWithConfigurationCache("Enumerates subprojects at execution time")
val outFile = layout.buildDirectory.file("npm-packages.txt")
outputs.file(outFile)
doLast {
val names = subprojects
.filter { it.plugins.hasPlugin("com.sphereon.gradle.plugin.npm-publication") }
.map { "@sphereon/idk-${it.name}" }
.sorted()
val f = outFile.get().asFile
f.parentFile.mkdirs()
f.writeText(names.joinToString(separator = "\n", postfix = "\n"))
logger.lifecycle("Wrote ${names.size} package name(s) to ${f.absolutePath}")
}
}
// =============================================================================
// Aggregate ktlint Tasks
// =============================================================================
tasks.register("ktlintCheckAll") {
group = "verification"
description = "Run ktlint checks across all IDK subprojects"
dependsOn(provider { subprojects.mapNotNull { it.tasks.findByName("ktlintCheck") } })
}
tasks.register("ktlintFormatAll") {
group = "formatting"
description = "Run ktlint format across all IDK subprojects"
dependsOn(provider { subprojects.mapNotNull { it.tasks.findByName("ktlintFormat") } })
}
// =============================================================================
// Aggregate detekt Tasks
// =============================================================================
tasks.register("detektAll") {
group = "verification"
description = "Run detekt static analysis across all IDK subprojects"
dependsOn(provider {
subprojects.flatMap { sub ->
sub.tasks.matching { it.name.startsWith("detekt") && !it.name.contains("Baseline") }
}
})
}
tasks.register("detektBaselineAll") {
group = "verification"
description = "Generate detekt baselines across all IDK subprojects"
dependsOn(provider {
subprojects.flatMap { sub ->
sub.tasks.matching { it.name.startsWith("detekt") && it.name.contains("Baseline") }
}
})
}
// =============================================================================
// Dokka HTML Documentation
// =============================================================================
// Modules to exclude from Dokka due to classpath conflicts, generated code, or deprecated status
val dokkaExcludedModules = setOf(
"tests-oid4vc-integration", // oid4vci integration tests
"lib-crypto-kms-rest-api", // OpenAPI generated sources
"lib-crypto-kms-provider-digidentity", // OpenAPI generated sources
"lib-all", // Aggregator module, no actual code
"lib-crypto-core", // Deprecated - placeholder only
"lib-data-link-http-client" // Deprecated - placeholder only
)
dokka {
moduleName.set("Identity-Development-Kit (IDK)")
moduleVersion.set(version.toString())
dokkaPublications.html {
outputDirectory.set(layout.buildDirectory.dir("dokka/html"))
includes.from(rootDir.resolve("dokka/Module.md"))
}
pluginsConfiguration.html {
footerMessage.set("© ${java.time.Year.now().value} Sphereon International B.V. | Creating Trust In A Digital World")
customStyleSheets.from(rootDir.resolve("dokka/sphereon-styles.css"))
}
}
// Apply Dokka plugin and aggregate dependencies only when a Dokka task is requested
val isDokkaRequested = gradle.startParameter.taskNames.any {
it.contains("dokka", ignoreCase = true)
}
if (isDokkaRequested) {
dependencies {
// Aggregate documentation from all subprojects that have Dokka applied
subprojects.forEach { subproject ->
if (subproject.name !in dokkaExcludedModules) {
subproject.plugins.withId("org.jetbrains.dokka") {
dokka(subproject)
}
}
}
}
subprojects {
if (name !in dokkaExcludedModules) {
apply(plugin = "org.jetbrains.dokka")
// Configure Dokka for each subproject with custom styles
extensions.configure<org.jetbrains.dokka.gradle.DokkaExtension> {
pluginsConfiguration.html {
customStyleSheets.from(rootDir.resolve("dokka/sphereon-styles.css"))
footerMessage.set("© ${java.time.Year.now().value} Sphereon International B.V. | Creating Trust In A Digital World")
}
val moduleMd = projectDir.resolve("dokka/module.md")
if (moduleMd.exists()) {
dokkaPublications.html {
includes.from(moduleMd)
}
}
}
// Ensure Dokka tasks run after copyGeneratedSources (for OpenAPI-generated code)
afterEvaluate {
tasks.matching { it.name.startsWith("dokka") }.configureEach {
tasks.findByName("copyGeneratedSources")?.let { mustRunAfter(it) }
}
}
}
}
}
abstract class VerifyWalletBoundaryTask : org.gradle.api.DefaultTask() {
@get:org.gradle.api.tasks.Input
abstract val violations: org.gradle.api.provider.ListProperty<String>
@org.gradle.api.tasks.TaskAction
fun verify() {
val found = violations.get()
if (found.isNotEmpty()) {
throw GradleException(
"AGPL boundary violation: non-wallet modules depend on wallet modules:\n" +
found.joinToString("\n"),
)
}
}
}
val verifyWalletBoundaryTask = tasks.register<VerifyWalletBoundaryTask>("verifyWalletBoundary") {
group = "verification"
description = "Fails if a project outside wallet depends on a project under wallet"
violations.set(emptyList())
}
gradle.projectsEvaluated {
val walletRoot = rootDir.toPath().resolve("wallet").toAbsolutePath().normalize()
verifyWalletBoundaryTask.configure {
violations.set(
rootProject.subprojects.flatMap { project ->
val projectPath = project.projectDir.toPath().toAbsolutePath().normalize()
if (projectPath.startsWith(walletRoot)) {
emptyList()
} else {
project.configurations.flatMap { configuration ->
configuration.dependencies
.filterIsInstance<org.gradle.api.artifacts.ProjectDependency>()
.mapNotNull { dependency ->
val dependencyProject = rootProject.findProject(dependency.path)
val dependencyPath = dependencyProject?.projectDir?.toPath()?.toAbsolutePath()?.normalize()
if (dependencyPath != null && dependencyPath.startsWith(walletRoot)) {
"${project.path} (${configuration.name}) -> ${dependencyProject.path}"
} else {
null
}
}
}
}
},
)
}
}
val rootCheckTask =
tasks.findByName("check")?.let { tasks.named("check") }
?: tasks.register("check") {
group = "verification"
description = "Runs verification tasks for the root project"
}
rootCheckTask.configure {
dependsOn(verifyWalletBoundaryTask)
}