-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.gradle.kts
438 lines (372 loc) · 13.7 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
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
import com.github.breadmoirai.githubreleaseplugin.ChangeLogSupplier
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED
import org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED
import org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED
import org.gradle.internal.impldep.org.joda.time.LocalDateTime
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.dsl.KotlinTargetContainerWithPresetFunctions
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmCompilation
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithHostTests
plugins {
application
kotlin("multiplatform") version "1.9.10"
kotlin("plugin.serialization") version "1.9.10"
id("com.apollographql.apollo3") version "4.+"
id("com.github.johnrengelman.shadow") version "8.+"
id("org.jlleitschuh.gradle.ktlint") version "11.+"
id("com.github.breadmoirai.github-release") version "2.4.+"
id("app.cash.sqldelight") version "2.+"
}
repositories {
mavenCentral()
}
application {
mainClass.set("MainKt")
}
val env = Env()
val output = Output(env)
val configurator = Configurator(env, output)
group = output.group
version = output.version
kotlin {
val jvmTarget = configurator.configureJvmTarget(this)
val nativeTarget = configurator.configureNativeTarget(this)
sourceSets {
val commonMain by getting {
dependencies {
val ktorVersion = "2.3.+"
implementation(kotlin("stdlib-common"))
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.+")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.+")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.+")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.+")
implementation("com.squareup.okio:okio:3.4.+")
implementation("net.mamoe.yamlkt:yamlkt:0.+")
implementation("com.apollographql.apollo3:apollo-api:4.+")
implementation("com.apollographql.apollo3:apollo-runtime:4.+")
implementation("com.github.ajalt.clikt:clikt:4.2.+")
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-auth:$ktorVersion")
implementation("io.ktor:ktor-client-logging:$ktorVersion")
implementation("io.ktor:ktor-client-serialization:$ktorVersion")
implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
implementation("io.ktor:ktor-server-core:$ktorVersion")
implementation("io.ktor:ktor-server-host-common:$ktorVersion")
implementation("io.ktor:ktor-server-cio:$ktorVersion")
implementation("io.ktor:ktor-server-cors:$ktorVersion")
implementation("io.ktor:ktor-server-forwarded-header:$ktorVersion")
implementation("io.ktor:ktor-server-content-negotiation:$ktorVersion")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
implementation("com.squareup.okio:okio-fakefilesystem:3.4.+")
implementation("com.willowtreeapps.assertk:assertk:0.+")
implementation("io.ktor:ktor-server-test-host:2.3.+")
}
}
// used by the 'getting' delegate
@Suppress("UNUSED_VARIABLE", "KotlinRedundantDiagnosticSuppress")
val jvmMain by getting {
dependsOn(commonMain)
dependencies {
implementation(kotlin("stdlib"))
implementation("org.slf4j:slf4j-simple:2.+")
implementation("io.ktor:ktor-client-cio:2.3.+")
implementation("app.cash.sqldelight:sqlite-driver:2.+")
}
}
// used by the 'getting' delegate
@Suppress("UNUSED_VARIABLE", "KotlinRedundantDiagnosticSuppress")
val jvmTest by getting {
dependsOn(commonTest)
}
// used by the 'getting' delegate
// @Suppress("UNUSED_VARIABLE", "KotlinRedundantDiagnosticSuppress")
// val macNativeMain by getting {
// dependsOn(commonMain)
// dependencies {
// implementation("io.ktor:ktor-client-curl:2.3.+")
// implementation("app.cash.sqldelight:native-driver:2.+")
// }
// }
// used by the 'getting' delegate
// @Suppress("UNUSED_VARIABLE", "KotlinRedundantDiagnosticSuppress")
// val macNativeTest by getting {
// dependsOn(commonTest)
// }
}
tasks {
withType<Test> {
useJUnitPlatform()
testLogging {
exceptionFormat = FULL
events = setOf(PASSED, FAILED, SKIPPED)
}
}
// make the JVM 'run' task work
withType<JavaExec> {
val jvmMainCompilation = jvmTarget.compilations.getByName<KotlinJvmCompilation>("main")
classpath(
files(
jvmMainCompilation.runtimeDependencyFiles,
jvmMainCompilation.output.allOutputs,
)
)
standardInput = System.`in`
}
// make the JVM 'jar' task work
withType<ShadowJar> {
archiveBaseName.set(output.artifact)
archiveClassifier.set("")
archiveVersion.set("")
isZip64 = true
val jvmMainCompilation = jvmTarget.compilations.getByName<KotlinJvmCompilation>("main")
from(jvmMainCompilation.output)
configurations = mutableListOf(
jvmMainCompilation.compileDependencyFiles,
jvmMainCompilation.runtimeDependencyFiles,
)
}
register<Copy>("prepareForPublish") {
group = "distribution"
description = "Prepare the project outputs for publishing"
val distributionsDir = output.getDistributionsDir()
val artifactName = output.artifact
val dependentTasks = mutableListOf("shadowJar")
if (nativeTarget != null) {
dependentTasks.add("${nativeTarget.name}Binaries")
}
dependsOn(*dependentTasks.toTypedArray()) // must be called only once with varargs
// take native if available
if (nativeTarget != null) {
from(output.getBinaryDir(nativeTarget.name)) {
include("$artifactName.kexe")
rename { if (it.endsWith(".kexe")) artifactName else it }
}
}
// take JAR anyway
from(output.getJarDir()) {
include("$artifactName.jar")
}
into(distributionsDir)
doLast {
println("Copied $artifactName artifact[s] to $distributionsDir")
}
}
register<Copy>("install") {
group = "application"
description = "Build the native executable and install it"
val installDir = output.getInstallDir()
val artifactName = output.artifact
if (nativeTarget == null) {
// JVM: copy the file to the root directory
dependsOn("shadowJar")
val jarDir = output.getJarDir()
from(jarDir) {
include("$artifactName.jar")
}
into(installDir)
doLast {
println("Copied $jarDir/$artifactName.jar to $installDir/$artifactName.jar")
}
} else {
// Native: copy the file to the programs directory
dependsOn("${nativeTarget.name}Binaries")
val binaryDir = output.getBinaryDir(nativeTarget.name)
from(binaryDir) {
include("$artifactName.kexe")
rename { artifactName }
}
into(installDir)
doLast {
println("Copied $binaryDir/$artifactName.kexe to $installDir/$artifactName")
}
}
} // install task
named("githubRelease") {
dependsOn("prepareForPublish")
}
} // tasks
} // kotlin
ktlint {
verbose.set(true)
outputToConsole.set(true)
enableExperimentalRules.set(true)
filter {
exclude { projectDir.toURI().relativize(it.file.toURI()).path.contains("/sqldelight/") }
exclude { projectDir.toURI().relativize(it.file.toURI()).path.contains("/generated/") }
}
}
apollo {
service("github") {
generateKotlinModels.set(true)
generateOptionalOperationVariables.set(false)
packageName.set("com.github.graphql")
outputDirConnection {
connectToKotlinSourceSet("commonMain")
}
}
}
sqldelight {
databases {
create(output.artifact) {
packageName.set(output.artifact)
}
}
}
githubRelease {
val writeToken = env.sysVar("GITHUB_TOKEN") { "<invalid>" }
if (writeToken == "<invalid>") println("Set \$GITHUB_TOKEN to enable GitHub releases.")
val commitish = env.sysVar("GITHUB_SHA") { "master" }
val prNumber = env.sysVar("GITHUB_PR_NUMBER")
val buildMoment = LocalDateTime.now()
val nowTag = buildMoment.toString("yyyy-MM-dd-HH-mm-ss")
val quality = env.sysVar("BUILD_QUALITY") { "Development" }
var directoryPrefix = ""
var prNumberPrefix = ""
var timestampSuffix = ""
when (quality) {
"GA" -> Unit
"PR" -> {
directoryPrefix = "pr/"
prNumberPrefix = if (prNumber.isNotBlank()) "$prNumber/" else ""
timestampSuffix = "/$nowTag"
}
else -> {
directoryPrefix = "dev/"
prNumberPrefix = ""
timestampSuffix = "/$nowTag"
}
}
val tag = "${directoryPrefix}${prNumberPrefix}v${output.version}$timestampSuffix"
val name = "[$quality] v${output.version}"
token(writeToken)
owner(output.repoOwner)
repo(output.repoName)
tagName(tag)
releaseName(name)
targetCommitish(commitish)
prerelease(quality != "GA")
val maxFetched = 15
val maxReported = 7
val bullet = "\n* "
val changelogConfig = closureOf<ChangeLogSupplier> {
currentCommit("HEAD")
lastCommit("HEAD~$maxFetched")
options("--format=oneline", "--abbrev-commit", "--max-count=$maxFetched")
}
val ignoredMessagesRegex = setOf(
"(?i).*bump.*version.*",
"(?i).*increase.*version.*",
"(?i).*version.*bump.*",
"(?i).*version.*increase.*",
"(?i).*merge.*request.*",
"(?i).*request.*merge.*",
"(?i).*merge.*",
).map(String::toRegex)
val changes = try {
changelog(changelogConfig)
.call()
.trim()
.split("\n")
.map { it.trim() }
.filterNot { ignoredMessagesRegex.any(it::matches) }
.take(maxReported)
} catch (t: Throwable) {
System.err.println("Failed to fetch Git history. Reason: ${t.message}")
emptyList()
}
val changesAsBullets = changes.joinToString(separator = bullet, prefix = bullet)
body(
when {
changes.isNotEmpty() -> "## Latest changes\n$changesAsBullets"
else -> "Explore commit history for latest changes."
}
)
val distributionsDir = output.getDistributionsDir()
val jarFile = file("$distributionsDir/${output.artifact}.jar")
val configFile = file("src/commonMain/resources/sample.config.yaml")
val unixFile = file("$distributionsDir/${output.artifact}")
val toInclude = mutableListOf(jarFile, configFile)
if (unixFile.exists()) toInclude += unixFile
releaseAssets(*toInclude.toTypedArray())
println("Configured GitHub release '$tag' for publishing. Run 'githubRelease' to publish.")
}
// region Utils
class Env {
enum class Platform(val targetName: String) { JVM("jvm"), MAC("macNative") }
enum class Arch { X86, ARM }
val currentPlatform = when {
sysProp("os.name") == "Mac OS X" -> Platform.MAC
else -> Platform.JVM
}
val currentArch = when {
sysProp("os.arch") in setOf("arm64", "aarch64") -> Arch.ARM
else -> Arch.X86
}
inline fun sysProp(name: String, default: () -> String = { "" }) = System.getProperty(name)
.takeIf { !it.isNullOrBlank() }
?: default()
inline fun gradleProp(name: String, default: () -> String = { "" }) = providers.gradleProperty(name).orNull
.takeIf { !it.isNullOrBlank() }
?: default()
inline fun sysVar(name: String, default: () -> String = { "" }) = System.getenv(name)
.takeIf { !it.isNullOrBlank() }
?: default()
}
class Output(private val env: Env) {
val group = env.sysVar("PROJECT_GROUP") { env.gradleProp("config.group") }
val artifact = env.sysVar("PROJECT_ARTIFACT") { env.gradleProp("config.artifact") }
val version = env.sysVar("PROJECT_VERSION") { env.gradleProp("config.version") }
val repoOwner = env.sysVar("REPO_OWNER") { env.gradleProp("config.gitHubRepoOwner") }
val repoName = env.sysVar("REPO_NAME") { env.gradleProp("config.gitHubRepoName") }
fun getInstallDir() = when (env.currentPlatform) {
Env.Platform.MAC -> "/usr/local/bin"
else -> env.sysProp("user.dir")
}.replace('/', File.separatorChar)
fun getJarDir() = "build/libs"
.replace('/', File.separatorChar)
fun getBinaryDir(targetName: String) = "build/bin/$targetName/${artifact}ReleaseExecutable"
.replace('/', File.separatorChar)
fun getDistributionsDir() = "build/distributions"
.replace('/', File.separatorChar)
}
class Configurator(private val env: Env, private val output: Output) {
fun configureJvmTarget(container: KotlinTargetContainerWithPresetFunctions) =
container.jvm(Env.Platform.JVM.targetName) {
compilations.all {
kotlinOptions.jvmTarget = "17"
compilerOptions.configure {
jvmTarget.set(JvmTarget.JVM_17)
}
}
println("Configured Kotlin target '$name'")
}
@Suppress("USELESS_CAST", "UNUSED_PARAMETER")
fun configureNativeTarget(container: KotlinTargetContainerWithPresetFunctions): KotlinNativeTargetWithHostTests? =
when (env.currentPlatform) {
// TODO – disabled temporarily until the build is fixed
Env.Platform.MAC -> null as? KotlinNativeTargetWithHostTests?
// when (env.currentArch) {
// Env.Arch.X86 -> container.macosX64(env.currentPlatform.targetName)
// Env.Arch.ARM -> container.macosArm64(env.currentPlatform.targetName)
// }
else -> null
}?.also { target ->
target.binaries {
executable(output.artifact) {
entryPoint = "main"
}
all {
binaryOptions["memoryModel"] = "experimental"
}
}
println("Configured Kotlin/Native target '${target.name}'")
}
}
// endregion