-
Notifications
You must be signed in to change notification settings - Fork 45
/
build.gradle.kts
409 lines (375 loc) · 15.4 KB
/
build.gradle.kts
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
/*
* Copyright (C) 2010-2019, Danilo Pianini and contributors listed in the main project"s alchemist/build.gradle file.
*
* This file is part of Alchemist, and is distributed under the terms of the
* GNU General Public License, with a linking exception,
* as described in the file LICENSE in the Alchemist distribution"s top directory.
*/
import Libs.incarnation
import Libs.alchemist
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.io.ByteArrayOutputStream
import java.net.URL
plugins {
alias(libs.plugins.dokka)
alias(libs.plugins.gitSemVer)
alias(libs.plugins.java.qa)
alias(libs.plugins.kotlin.jvm)
alias(libs.plugins.kotlin.qa)
alias(libs.plugins.multiJvmTesting)
alias(libs.plugins.orchid)
alias(libs.plugins.publishOnCentral)
alias(libs.plugins.shadowJar)
alias(libs.plugins.taskTree)
}
apply(plugin = rootProject.libs.plugins.orchid.id)
val Provider<PluginDependency>.id get() = get().pluginId
allprojects {
with(rootProject.libs.plugins) {
apply(plugin = java.qa.id)
apply(plugin = multiJvmTesting.id)
apply(plugin = kotlin.qa.id)
apply(plugin = taskTree.id)
apply(plugin = shadowJar.id)
}
apply(plugin = "org.danilopianini.git-sensitive-semantic-versioning")
apply(plugin = "java-library")
apply(plugin = "kotlin")
apply(plugin = "build-dashboard")
apply(plugin = "org.jetbrains.dokka")
apply(plugin = "org.danilopianini.publish-on-central")
multiJvm {
jvmVersionForCompilation.set(11)
maximumSupportedJvmVersion.set(latestJava)
}
repositories {
google()
mavenCentral()
jcenter {
content {
onlyForConfigurations(
"orchidCompileClasspath",
"orchidRuntimeClasspath"
)
}
}
// for tornadofx 2.0.0 snapshot release
maven {
url = uri("https://oss.sonatype.org/content/repositories/snapshots")
content {
includeGroup("no.tornado")
}
}
}
dependencies {
with(rootProject.libs) {
compileOnly(spotbugs.annotations)
implementation(Libs.slf4j_api)
implementation(kotlin("stdlib-jdk8"))
implementation(kotlin("reflect"))
implementation(Libs.thread_inheritable_resource_loader)
testCompileOnly(spotbugs.annotations)
// Test implementation: JUnit 5 + Kotest + Mockito + Mockito-Kt
testImplementation(bundles.testing.compile)
// Test runtime: Junit engine
testRuntimeOnly(bundles.testing.runtimeOnly)
// executable jar packaging
}
if ("incarnation" in project.name) {
runtimeOnly(rootProject)
}
}
// COMPILE
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.withType<KotlinCompile> {
kotlinOptions {
jvmTarget = "1.8"
freeCompilerArgs = listOf("-Xjvm-default=all") // Enable default methods in Kt interfaces
}
}
// TEST AND COVERAGE
tasks.withType<Test> {
testLogging {
events("passed", "skipped", "failed", "standardError")
exceptionFormat = TestExceptionFormat.FULL
}
useJUnitPlatform()
}
// CODE QUALITY
javaQA {
checkstyle {
additionalConfiguration.set(
"""
<module name="RegexpSingleline">
<property name="severity" value="error" />
<property name="format" value="Math\s*\.\s*random\s*\(\s*\)" />
<property name="fileExtensions" value="java,xtend,scala,kt" />
<property name="message"
value="Don't use Math.random() inside Alchemist. Breaks stuff." />
</module>
<module name="RegexpSingleline">
<property name="severity" value="error" />
<property name="format" value="class\s*\.\s*forName\s*\(" />
<property name="fileExtensions" value="java,xtend,scala,kt" />
<property name="message"
value="Use the library to load classes and resources. Breaks grid otherwise." />
</module>
<module name="RegexpSingleline">
<property name="severity" value="error" />
<property name="format" value="class\s*\.\s*getResource" />
<property name="fileExtensions" value="java,xtend,scala,kt" />
<property name="message"
value="Use the library to load classes and resources. Breaks grid otherwise." />
</module>
<module name="RegexpSingleline">
<property name="severity" value="error" />
<property name="format" value="class\s*\.\s*getClassLoader" />
<property name="fileExtensions" value="java,xtend,scala,kt" />
<property name="message"
value="Use the library to load classes and resources. Breaks grid otherwise." />
</module>
<module name="RegexpSingleline">
<property name="severity" value="warning" />
<property name="format" value="@author" />
<property name="fileExtensions" value="java,xtend,scala,kt" />
<property name="message"
value="Do not use @author. Changes and authors are tracked by the content manager." />
</module>
""".trimIndent()
)
additionalSuppressions.set(
"""
<suppress files=".*[\\/]expressions[\\/]parser[\\/].*" checks=".*"/>
<suppress files=".*[\\/]biochemistrydsl[\\/].*" checks=".*"/>
""".trimIndent()
)
}
}
tasks.withType<com.github.spotbugs.snom.SpotBugsTask> {
reports {
create("html") { enabled = true }
}
}
// PUBLISHING
tasks.withType<Javadoc> {
// Disable Javadoc, use Dokka.
enabled = false
}
if (System.getenv("CI") == true.toString()) {
signing {
val signingKey: String? by project
val signingPassword: String? by project
useInMemoryPgpKeys(signingKey, signingPassword)
}
}
group = "it.unibo.alchemist"
val repoSlug = "AlchemistSimulator/Alchemist"
publishOnCentral {
projectDescription.set(extra["projectDescription"].toString())
projectLongName.set(extra["projectLongName"].toString())
licenseName.set("GPL 3.0 with linking exception")
licenseUrl.set("https://github.com/$repoSlug/blob/develop/LICENSE.md")
scmConnection.set("git:[email protected]:$repoSlug.git")
repository("https://maven.pkg.github.com/${repoSlug.toLowerCase()}") {
user.set("DanySK")
password.set(System.getenv("GITHUB_TOKEN"))
}
}
publishing.publications {
withType<MavenPublication> {
pom {
developers {
developer {
name.set("Danilo Pianini")
email.set("[email protected]")
url.set("http://www.danilopianini.org")
roles.set(mutableSetOf("architect", "developer"))
}
}
}
}
}
// Shadow Jar
tasks.withType<ShadowJar> {
manifest {
attributes(
mapOf(
"Implementation-Title" to "Alchemist",
"Implementation-Version" to rootProject.version,
"Main-Class" to "it.unibo.alchemist.Alchemist",
"Automatic-Module-Name" to "it.unibo.alchemist"
)
)
}
exclude("ant_tasks/")
exclude("about_files/")
exclude("help/about/")
exclude("build")
exclude(".gradle")
exclude("build.gradle")
exclude("gradle")
exclude("gradlew")
exclude("gradlew.bat")
isZip64 = true
mergeServiceFiles()
destinationDirectory.set(file("${rootProject.buildDir}/shadow"))
if ("full" in project.name || "incarnation" in project.name || project == rootProject) {
// Run the jar and check the output
val testShadowJar = tasks.register<Exec>("${this.name}-testWorkingOutput") {
val javaExecutable = org.gradle.internal.jvm.Jvm.current().javaExecutable.absolutePath
val command = arrayOf(javaExecutable, "-jar", archiveFile.get().asFile.absolutePath, "--help")
commandLine(*command)
val interceptOutput = ByteArrayOutputStream()
val interceptError = ByteArrayOutputStream()
standardOutput = interceptOutput
errorOutput = interceptError
isIgnoreExitValue = true
doLast {
val exit = executionResult.get().exitValue
require(exit == 0) {
val outputs = listOf(interceptOutput, interceptError).map {
String(it.toByteArray(), Charsets.UTF_8)
}
outputs.forEach { text ->
for (illegalKeyword in listOf("SLF4J", "NOP")) {
require(illegalKeyword !in text) {
"""
$illegalKeyword found while printing the help. Complete output:
$text
""".trimIndent()
}
}
}
"""
Process '${command.joinToString(" ")}' exited with $exit
Output:
${outputs[0]}
Error:
${outputs[0]}
""".trimIndent()
}
}
}
this.finalizedBy(testShadowJar)
}
}
}
/*
* Root project additional configuration
*/
evaluationDependsOnChildren()
dependencies {
// Depend on subprojects whose presence is necessary to run
listOf("interfaces", "engine", "loading").forEach { api(alchemist(it)) } // Execution requirements
with(libs.apache.commons) {
implementation(cli)
implementation(io)
implementation(lang3)
}
implementation(libs.apache.commons.cli)
implementation(libs.guava)
implementation(libs.logback)
testRuntimeOnly(incarnation("protelis"))
testRuntimeOnly(incarnation("sapere"))
testRuntimeOnly(incarnation("biochemistry"))
testRuntimeOnly(alchemist("cognitive-agents"))
testRuntimeOnly(alchemist("physical-agents"))
// Populate the dependencies for Orchid
orchidImplementation(libs.orchid.core)
orchidRuntimeOnly(libs.bundles.orchid)
}
// WEBSITE
fun String.toVersion() = org.danilopianini.gradle.gitsemver.SemanticVersion.fromStringOrNull(this)
?: throw IllegalStateException("Not a valid semantic version: $this")
val projectVersion = gitSemVer.computeVersion().toVersion()
@ExperimentalUnsignedTypes
val isMarkedStable = projectVersion.preRelease.isEmpty()
tasks.withType<org.jetbrains.dokka.gradle.DokkaCollectorTask> {
val type = Regex("^dokka(\\w+)Collector\$").matchEntire(name)?.destructured?.component1()?.toLowerCase()
?: throw IllegalStateException("task named $name does not match the expected name pattern for dokka collection tasks")
if (type.equals("html", ignoreCase = true) || type.equals("javadoc", ignoreCase = true)) {
// Bind Dokka Javadoc and Dokka HTML to Orchid
outputDirectory.set(file("$buildDir/docs/orchid/$type"))
listOf(tasks.orchidServe, tasks.orchidBuild).forEach { it.get().dependsOn(this) }
}
}
orchid {
theme = "Editorial"
// Determine whether it's a deployment or a dry run
baseUrl = "https://alchemistsimulator.github.io/${if (isMarkedStable) "" else "latest/"}"
// Fetch the latest version of the website, if this one is more recent enable deploy
val versionRegex =
""".*Currently\s*(.+)\.\s*Created""".toRegex()
val matchedVersions: List<String> = runCatching {
URL(baseUrl).openConnection().getInputStream().use { stream ->
stream.bufferedReader().lineSequence()
.flatMap { line ->
versionRegex.find(line)?.groupValues?.last()?.let { sequenceOf(it) } ?: emptySequence()
}
.toList()
}
}.getOrDefault(emptyList())
val shouldDeploy = matchedVersions
.takeIf { it.size == 1 }
?.first()
?.let { projectVersion > it.toVersion() }
?: false
githubToken = System.getenv("githubToken")
?: project.findProperty("githubToken")?.toString()
?: System.getenv("GITHUB_TOKEN")
dryDeploy = shouldDeploy.not().toString()
println(
when (matchedVersions.size) {
0 -> "Unable to fetch the current site version from $baseUrl"
1 -> "Website $baseUrl is at version ${matchedVersions.first()}"
else -> "Multiple site versions fetched from $baseUrl: $matchedVersions"
} + ". Orchid deployment ${if (shouldDeploy) "enabled" else "set as dry run"}."
)
}
gradle.taskGraph.whenReady {
if (hasTask(tasks.orchidDeploy.get()) &&
orchid.dryDeploy?.toBoolean()?.not() == true &&
orchid.githubToken.isNullOrBlank()
) {
throw IllegalStateException("Real deployment requested but no GitHub deployment token set")
}
}
val orchidSeedConfiguration by tasks.register("orchidSeedConfiguration") {
/*
* Detect files
*/
val configFolder = listOf(projectDir.toString(), "src", "orchid", "resources")
.joinToString(separator = File.separator)
val baseConfigFile = file("$configFolder${File.separator}config-origin.yml")
@org.gradle.api.tasks.InputFile
fun baseConfig(): File = baseConfigFile
val finalConfig = file("$configFolder${File.separator}config.yml")
@org.gradle.api.tasks.OutputFile
fun finalConfig(): File = finalConfig
doLast {
/*
* Compute Kdoc targets
*/
val baseConfig = baseConfigFile.readText()
val deploymentConfiguration = if (!baseConfig.contains("services:")) {
"""
services:
publications:
stages:
- type: githubPages
username: 'DanySK'
commitUsername: Danilo Pianini
commitEmail: [email protected]
repo: 'AlchemistSimulator/${if (isMarkedStable) "alchemistsimulator.github.io" else "latest" }'
branch: ${if (isMarkedStable) "master" else "gh-pages"}
publishType: CleanBranchMaintainHistory
""".trimIndent()
} else ""
finalConfig.writeText(baseConfig + deploymentConfiguration)
}
}
tasks.orchidClasses.orNull!!.dependsOn(orchidSeedConfiguration)