generated from korlibs/korlibs-library-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.gradle.kts
1153 lines (1026 loc) · 46.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
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import com.google.gson.*
import com.google.gson.JsonParser
import groovy.json.*
import groovy.util.*
import org.gradle.api.internal.tasks.testing.*
import org.gradle.api.tasks.testing.logging.*
import org.gradle.jvm.tasks.Jar
import org.gradle.plugins.signing.signatory.internal.pgp.*
import org.jetbrains.dokka.gradle.*
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.targets.js.ir.*
import java.net.*
import java.util.*
import java.util.concurrent.*
plugins {
kotlin("multiplatform") version "2.0.10"
id("com.android.library") version "8.2.2"
id("org.jetbrains.kotlinx.kover") version "0.8.3" apply false
id("org.jetbrains.kotlinx.binary-compatibility-validator") version "0.16.2"
id("org.jetbrains.dokka") version "1.9.20"
//id("org.ysb33r.ivypot") version "1.0.0"
`maven-publish`
signing
}
var REAL_VERSION = System.getenv("FORCED_VERSION")
?.replaceFirst(Regex("^refs/tags/"), "")
?.replaceFirst(Regex("^v"), "")
?.replaceFirst(Regex("^w"), "")
?.replaceFirst(Regex("^z"), "")
//?: rootProject.findProperty("version")
?: "999.0.0.999"
//val REAL_VERSION = System.getenv("FORCED_VERSION") ?: "999.0.0.999"
val JVM_TARGET = JvmTarget.JVM_1_8
val JDK_VERSION = org.gradle.api.JavaVersion.VERSION_1_8
//val JVM_TARGET = JvmTarget.JVM_11
//val JDK_VERSION = org.gradle.api.JavaVersion.VERSION_11
val GROUP = "com.soywiz"
kotlin {
jvm()
androidTarget()
}
allprojects {
repositories {
mavenCentral()
google()
gradlePluginPortal()
//maven("https://maven.pkg.jetbrains.space/public/p/amper/amper")
//maven("https://www.jetbrains.com/intellij-repository/releases")
//maven("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies")
}
version = REAL_VERSION
group = GROUP
project.apply(plugin = "kotlin-multiplatform")
project.apply(plugin = "android-library")
java.toolchain.languageVersion = JavaLanguageVersion.of(JDK_VERSION.majorVersion)
kotlin.jvmToolchain(JDK_VERSION.majorVersion.toInt())
afterEvaluate {
tasks.withType(Test::class) {
//this.javaLauncher.set()
this.javaLauncher.set(javaToolchains.launcherFor {
// 17 is latest at the current moment
languageVersion.set(JavaLanguageVersion.of(JDK_VERSION.majorVersion))
})
}
}
android {
compileOptions {
sourceCompatibility = JDK_VERSION
targetCompatibility = JDK_VERSION
}
//signingConfigs {
// debug {
// […]
// }
// release {
// […]
// }
//}
compileSdk = 33
namespace = "com.soywiz.${project.name.replace("-", ".")}"
defaultConfig {
minSdk = 20
}
// defaultConfig {
// applicationId "[…]"
// minSdk 25
// targetSdk 33
// compileSdk 33
// versionCode 33
// versionName '33'
// testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// signingConfig signingConfigs.release
// }
//buildTypes {
// release {
// […]
// }
//}
}
MicroAmper(this).configure()
}
fun Project.doOnce(uniqueName: String, block: () -> Unit) {
val key = "doOnce-$uniqueName"
if (!rootProject.extra.has(key)) {
rootProject.extra.set(key, true)
block()
}
}
open class DenoTestTask : AbstractTestTask() {
//open class DenoTestTask : KotlinTest() {
//var isDryRun by org.jetbrains.kotlin.gradle.utils.property { false }
init {
this.group = "verification"
this.dependsOn("compileTestDevelopmentExecutableKotlinJs")
}
//@Option(option = "tests", description = "Specify tests to execute as a filter")
//@Input
//var tests: String = ""
init {
this.reports {
junitXml.outputLocation.set(project.file("build/test-results/jsDenoTest/"))
html.outputLocation.set(project.file("build/reports/tests/jsDenoTest/"))
}
binaryResultsDirectory.set(project.file("build/test-results/jsDenoTest/binary"))
//reports.enabledReports["junitXml"]!!.optional
//reports.junitXml.outputLocation.opt
//reports.enabledReports.clear()
//reports.junitXml.outputLocation.set(project.file("build/deno-test-results"))
}
override fun createTestExecuter(): TestExecuter<out TestExecutionSpec> {
return DenoTestExecuter(this.project, this.filter)
}
//override fun createTestExecuter(): TestExecuter<out TestExecutionSpec> = TODO()
override fun createTestExecutionSpec(): TestExecutionSpec = DenoTestExecutionSpec()
init {
outputs.upToDateWhen { false }
}
class DenoTestExecuter(val project: Project, val filter: TestFilter) : TestExecuter<DenoTestExecutionSpec> {
private fun Project.fullPathName(): String {
//KotlinTest
if (this.parent == null) return this.name
return this.parent!!.fullPathName() + ":" + this.name
}
override fun execute(testExecutionSpec: DenoTestExecutionSpec, testResultProcessor: TestResultProcessor) {
val baseTestFileNameBase = this.project.fullPathName().trim(':').replace(':', '-') + "-test"
val baseTestFileName = "$baseTestFileNameBase.mjs"
val runFile = File(this.project.rootProject.rootDir, "build/js/packages/$baseTestFileNameBase/kotlin/$baseTestFileName.deno.mjs")
runFile.parentFile.mkdirs()
runFile.writeText(
//language=js
"""
var describeStack = []
globalThis.describe = (name, callback) => { describeStack.push(name); try { callback() } finally { describeStack.pop() } }
globalThis.it = (name, callback) => { return Deno.test({ name: describeStack.join(".") + "." + name, fn: callback}) }
globalThis.xit = (name, callback) => { return Deno.test({ name: describeStack.join(".") + "." + name, ignore: true, fn: callback}) }
function exists(path) { try { Deno.statSync(path); return true } catch (e) { return false } }
// Polyfill required for kotlinx-coroutines that detects window
window.postMessage = (message, targetOrigin) => { const ev = new Event('message'); ev.source = window; ev.data = message; window.dispatchEvent(ev); }
const file = './${baseTestFileName}';
if (exists(file)) await import(file)
""".trimIndent())
//testResultProcessor.started()
val process = ProcessBuilder(buildList<String> {
add("deno")
add("test")
add("--unstable-ffi")
add("--unstable-webgpu")
add("-A")
if (filter.includePatterns.isEmpty()) {
add("--filter=${filter.includePatterns.joinToString(",")}")
}
add("--junit-path=${project.file("build/test-results/jsDenoTest/junit.xml").absolutePath}")
add(runFile.absolutePath)
}).directory(runFile.parentFile)
.start()
var id = 0
val buffered = process.inputStream.bufferedReader()
var capturingOutput = false
var currentTestId: String? = null
var currentTestExtra: String = "ok"
var failedCount = 0
fun flush() {
if (currentTestId != null) {
try {
val type = when {
currentTestExtra.contains("skip", ignoreCase = true) || currentTestExtra.contains("ignored", ignoreCase = true) -> TestResult.ResultType.SKIPPED
currentTestExtra.contains("error", ignoreCase = true) || currentTestExtra.contains("failed", ignoreCase = true) -> TestResult.ResultType.FAILURE
currentTestExtra.contains("ok", ignoreCase = true) -> TestResult.ResultType.SUCCESS
else -> TestResult.ResultType.SUCCESS
}
if (type == TestResult.ResultType.FAILURE) {
testResultProcessor.output(currentTestId, DefaultTestOutputEvent(TestOutputEvent.Destination.StdErr, "FAILED\n"))
testResultProcessor.failure(currentTestId, DefaultTestFailure.fromTestFrameworkFailure(Exception("FAILED").also { it.stackTrace = arrayOf() }, null))
failedCount++
}
testResultProcessor.completed(currentTestId, TestCompleteEvent(System.currentTimeMillis(), type))
} catch (e: Throwable) {
//System.err.println("COMPLETED_ERROR: ${e}")
e.printStackTrace()
}
currentTestId = null
}
}
testResultProcessor.started(DefaultTestSuiteDescriptor("deno", "deno"), TestStartEvent(System.currentTimeMillis()))
for (line in buffered.lines()) {
println("::: $line")
when {
line == "------- output -------" -> {
capturingOutput = true
}
line == "----- output end -----" -> {
capturingOutput = false
}
capturingOutput -> {
testResultProcessor.output(currentTestId, DefaultTestOutputEvent(TestOutputEvent.Destination.StdOut, "$line\n"))
}
line.contains("...") -> {
//DefaultNestedTestSuiteDescriptor()
flush()
val (name, extra) = line.split("...").map { it.trim() }
//currentTestId = "$name${id++}"
currentTestId = "deno.myid${id++}"
//val demo = CompositeId("Unit", "Name${id++}")
//val descriptor = DefaultTestMethodDescriptor(currentTestId, name.substringBeforeLast('.'), name.substringAfterLast('.'))
val descriptor = DefaultTestMethodDescriptor(currentTestId, name.substringBeforeLast('.'), name)
currentTestExtra = extra
testResultProcessor.started(
descriptor,
TestStartEvent(System.currentTimeMillis())
)
}
}
}
flush()
testResultProcessor.completed("deno", TestCompleteEvent(System.currentTimeMillis(), if (failedCount == 0) TestResult.ResultType.SUCCESS else TestResult.ResultType.FAILURE))
process.waitFor()
System.err.print(process.errorStream.readBytes().decodeToString())
}
override fun stopNow() {
}
}
class DenoTestExecutionSpec : TestExecutionSpec
}
class SonatypeProps(val project: Project) {
// Signing
val signingKey: String? = System.getenv("ORG_GRADLE_PROJECT_signingKey") ?: project.findProperty("signing.signingKey")?.toString()
val signingPassword: String? = System.getenv("ORG_GRADLE_PROJECT_signingPassword") ?: project.findProperty("signing.password")?.toString()
val globalSignatories: CachedInMemoryPgpSignatoryProvider? = when {
signingKey != null && signingPassword != null -> CachedInMemoryPgpSignatoryProvider(signingKey, signingPassword)
else -> null
}
val sonatypePublishUserNull: String? =
(System.getenv("SONATYPE_USERNAME") ?: rootProject.findProperty("SONATYPE_USERNAME")?.toString() ?: project.findProperty("sonatypeUsername")
?.toString())
val sonatypePublishPasswordNull: String? =
(System.getenv("SONATYPE_PASSWORD") ?: rootProject.findProperty("SONATYPE_PASSWORD")?.toString() ?: project.findProperty("sonatypePassword")
?.toString())
val sonatype: Sonatype? = when {
sonatypePublishUserNull != null && sonatypePublishPasswordNull != null -> Sonatype(sonatypePublishUserNull, sonatypePublishPasswordNull)
else -> null
}
val stagedRepositoryId: String? by lazy {
System.getenv("stagedRepositoryId")
?: findProperty("stagedRepositoryId")?.toString()
?: File("stagedRepositoryId").takeIf { it.exists() }?.readText()?.trim()
}
open class StartReleasingMavenCentral : DefaultTask() {
@Input
@Optional
var sonatype: Sonatype? = null
@TaskAction
fun action() {
val profileId = sonatype!!.findProfileIdByGroupId("com.soywiz")
val stagedRepositoryId = sonatype!!.startStagedRepository(profileId)
println("profileId=$profileId")
println("stagedRepositoryId=$stagedRepositoryId")
GithubCI.setOutput("stagedRepositoryId", stagedRepositoryId)
File("stagedRepositoryId").writeText(stagedRepositoryId)
}
}
open class ReleaseMavenCentralTask : DefaultTask() {
@Input
@Optional
var sonatype: Sonatype? = null
@Input
@Optional
var repositoryId: String? = null
@TaskAction
fun action() {
//if (!sonatype.releaseGroupId(rootProject.group.toString())) {
try {
if (!sonatype!!.releaseRepositoryID(repositoryId)) {
error("Can't promote artifacts. Check log for details")
}
} finally {
File("stagedRepositoryId").delete()
}
}
}
fun createTasks(project: Project) = with(project) {
if (sonatype != null) {
tasks.create("startReleasingMavenCentral", StartReleasingMavenCentral::class) {
this.sonatype = this@SonatypeProps.sonatype
}
rootProject.tasks.create<ReleaseMavenCentralTask>("releaseMavenCentral") {
this.sonatype = this@SonatypeProps.sonatype
this.repositoryId = this@SonatypeProps.stagedRepositoryId
}
}
if (stagedRepositoryId != null) {
println("stagedRepositoryId=$stagedRepositoryId")
}
}
}
val sonatypeProps = SonatypeProps(rootProject)
sonatypeProps.createTasks(rootProject)
subprojects {
//apply<KotlinMultiplatformPlugin>()
apply(plugin = "kotlin-multiplatform")
apply(plugin = "maven-publish")
apply(plugin = "signing")
kotlin {
js {
//nodejs()
browser {
compilerOptions {
target.set("es2015")
}
}
}
}
kotlin {
//if (targets.any { it.name.contains("android") }) {
androidTarget {
this.compilerOptions.jvmTarget.set(JVM_TARGET)
publishAllLibraryVariants()
//publishLibraryVariants("release", "debug")
}
//}
}
tasks {
//println(this.findByName("compileTestKotlinJs")!!::class)
//println(this.findByName("compileTestKotlinJs")!!.dependsOn?.toList())
//println(this.findByName("compileTestKotlinJs")?.outputs?.files?.toList())
val jsDenoTest by creating(DenoTestTask::class) {
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask::class) {
compilerOptions.suppressWarnings.set(true)
// @TODO: We should actually, convert warnings to errors and start removing warnings
compilerOptions.freeCompilerArgs.add("-nowarn")
//println("${project.name} ${this::class.java} : ${this.name}")
}
//class KotlinNativeLinkDoLast : Copy() {
//}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink::class) {
// /Users/soywiz/projects/korge-korlibs/korlibs-io/build/bin/iosSimulatorArm64/debugTest
//println(this.target)
//val target = Regex("^link(.*?)Test.*$").find(this.name)?.groupValues?.getOrNull(1)?.replaceFirstChar { it.lowercaseChar() }
//println(target)
//val compileTaskName = this.name.replace(Regex("^link(.*?)Test.*$")) { "compileTestKotlin${it.groupValues[1]}" }
//val compileTask = tasks.findByName(compileTaskName) as? KotlinNativeCompile?
val folder = this.outputs.files.toList().firstOrNull()
val fromFolder = File(project.projectDir, "testresources")
if (folder != null) {
val copyAfterLink = tasks.create("${this.name}CopyResources", Copy::class)
copyAfterLink.from(fromFolder)
copyAfterLink.into(folder)
this.dependsOn(copyAfterLink)
}
}
tasks.withType(org.gradle.api.tasks.testing.AbstractTestTask::class) {
testLogging {
events = mutableSetOf(
TestLogEvent.SKIPPED,
TestLogEvent.FAILED,
TestLogEvent.STANDARD_OUT, TestLogEvent.STANDARD_ERROR
)
exceptionFormat = TestExceptionFormat.FULL
showStandardStreams = true
showStackTraces = true
}
}
kotlin.targets.withType(KotlinJsIrTarget::class) {
//println("TARGET: $this")
//nodejs()
browser {
//testTask { useKarma { useChromeHeadless() } }
testRuns.getByName(KotlinTargetWithTests.DEFAULT_TEST_RUN_NAME).executionTask.configure {
useKarma {
useChromeHeadless()
File(project.rootProject.rootDir, "karma.config.d").takeIf { it.exists() }?.let {
useConfigDirectory(it)
}
}
}
}
}
fun String.escape(): String = buildString(length) {
for (c in this@escape) when (c) { '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t"); '\\' -> append("\\\\"); else -> append(c) }
}
fun String.quote(): String = "\"${escape()}\""
open class TestProcessResourcesLast : DefaultTask() {
@Input
lateinit var dirs: List<File>
@TaskAction
fun action() {
for (dir in dirs) {
for (file in dir.walkTopDown()) {
if (file.isDirectory) {
//println("file=$file")
File(file, "\$catalog.json").writeText(generateCatalog(file))
}
}
}
}
fun generateCatalog(folder: File): String = buildString {
appendLine("{")
for (file in folder.listFiles() ?: arrayOf()) {
val fileName = if (file.isDirectory) "${file.name}/" else file.name
appendLine(" ${fileName.quote()} : [${file.length()}, ${file.lastModified()}],")
}
appendLine("}")
}
}
for (taskName in listOf("jsTestProcessResources", "wasmTestProcessResources")) {
tasks.findByName(taskName)?.apply {
this.dependsOn(tasks.create("${taskName}CopyResources", TestProcessResourcesLast::class).also {
it.dirs = this.outputs.files.toList().filter { it.isDirectory }
})
}
}
// This is required on linux because testResources / testresources mismatch (that doesn't happen on Windows or Mac)
// See https://github.com/korlibs/korge-korlibs/issues/6
tasks.withType(ProcessResources::class) {
if (this.name.contains("js", ignoreCase = true) || this.name.contains("wasm", ignoreCase = true)) {
if (this.name.contains("Test")) {
from("testresources")
}
from("resources")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
//println(tasks.findByName("jsProcessResources")!!::class)
// Publishing
run {
publishing {
repositories {
if (sonatypeProps.sonatype != null) {
maven {
credentials {
username = sonatypeProps.sonatype.user
password = sonatypeProps.sonatype.pass
}
url = when {
version.toString().contains("-SNAPSHOT") -> uri("https://oss.sonatype.org/content/repositories/snapshots/")
sonatypeProps.stagedRepositoryId != null -> uri("https://oss.sonatype.org/service/local/staging/deployByRepositoryId/${sonatypeProps.stagedRepositoryId}/")
else -> uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
}
doOnce("showDeployTo") { logger.info("DEPLOY mavenRepository: $url") }
}
}
}
publications.withType(MavenPublication::class) {
//println(this.artifacts.stream().map { it.file })
//copyArtifactsToDirectory.get().from(this.artifacts.stream().map { it.file })
val publication = this
val jarTaskName = "${publication.name}JavadocJar"
//println(jarTaskName)
val javadocJar = tasks.create<Jar>(jarTaskName) {
archiveClassifier.set("javadoc")
archiveBaseName.set(jarTaskName)
}
publication.artifact(javadocJar)
//println("PUBLICATION: ${publication.name}")
fun getCustomProp(key: String, defaultValue: String): String {
// @TODO: Actually be able to override it
return defaultValue
}
//if (multiplatform) {
//if (!isGradlePluginMarker) {
run {
val defaultGitUrl = "https://github.com/korlibs/korge-korlibs"
publication.pom.also { pom ->
pom.name.set(project.name)
pom.description.set(project.description ?: getCustomProp("project.description", project.description ?: project.name))
pom.url.set(getCustomProp("project.scm.url", defaultGitUrl))
pom.licenses {
license {
name.set(getCustomProp("project.license.name", "MIT"))
url.set(getCustomProp("project.license.url", "https://raw.githubusercontent.com/korlibs/korge-korlibs/main/LICENSE"))
}
}
pom.developers {
developer {
id.set(getCustomProp("project.author.id", "soywiz"))
name.set(getCustomProp("project.author.name", "Carlos Ballesteros Velasco"))
email.set(getCustomProp("project.author.email", "soywiz@gmail.com"))
}
}
pom.scm {
url.set(getCustomProp("project.scm.url", defaultGitUrl))
}
}
publication.pom.withXml {
val root = NodeList(listOf(this@withXml.asNode()))
//println("baseProjectName=$baseProjectName")
val packaging = root.getAt("packaging").text()
//println("---------------")
//println("root=$root")
//println("packaging=" + (root.getAt("packaging")))
//println("packaging=" + root.getAt("packaging"))
//println("packaging.text=" + root.getAt("packaging").text())
if (packaging == "aar") {
val nodes: NodeList = root.getAt("dependencies").getAt("dependency").getAt("scope")
for (node in nodes as List<Node>) {
node.setValue("compile")
//println("node=$node setValue=compile")
}
}
}
}
}
}
}
// Signing
if (sonatypeProps.globalSignatories != null) {
signing {
sign(publishing.publications)
this.signatories = sonatypeProps.globalSignatories
}
}
//println(KotlinCompilerVersion.VERSION)
}
open class CachedInMemoryPgpSignatoryProvider(signingKey: String?, signingPassword: String?) : InMemoryPgpSignatoryProvider(signingKey, signingPassword) {
var cachedPhpSignatory: PgpSignatory? = null
override fun getDefaultSignatory(project: Project): PgpSignatory? {
//project.rootProject
//println("getDefaultSignatory:$project")
if (cachedPhpSignatory == null) {
cachedPhpSignatory = super.getDefaultSignatory(project)
}
return cachedPhpSignatory
}
}
open class Sonatype(
val user: String,
val pass: String,
val BASE: String = DEFAULT_BASE
) {
companion object {
val DEFAULT_BASE = "https://oss.sonatype.org/service/local/staging"
private val BASE = DEFAULT_BASE
//fun fromGlobalConfig(): Sonatype {
// val props = Properties().also { it.load(File(System.getProperty("user.home") + "/.gradle/gradle.properties").readText().reader()) }
// return Sonatype(props["sonatypeUsername"].toString(), props["sonatypePassword"].toString(), DEFAULT_BASE)
//}
//fun fromProject(project: Project): Sonatype {
// return Sonatype(project.sonatypePublishUser, project.sonatypePublishPassword)
//}
//@JvmStatic
//fun main(args: Array<String>) {
// val sonatype = fromGlobalConfig()
// sonatype.releaseGroupId("korlibs")
//}
}
fun releaseGroupId(groupId: String = "korlibs"): Boolean {
println("Trying to release groupId=$groupId")
val profileId = findProfileIdByGroupId(groupId)
println("Determined profileId=$profileId")
val repositoryIds = findProfileRepositories(profileId)
if (repositoryIds.isEmpty()) {
println("Can't find any repositories for profileId=$profileId for groupId=$groupId. Artifacts weren't upload?")
return false
}
return releaseRepositoryIDs(repositoryIds)
}
fun releaseRepositoryID(repositoryId: String?): Boolean {
val repositoryIds = listOfNotNull(repositoryId)
if (repositoryIds.isEmpty()) return false
return releaseRepositoryIDs(repositoryIds)
}
fun releaseRepositoryIDs(repositoryIds: List<String>): Boolean {
val repositoryIds = repositoryIds.toMutableList()
val totalRepositories = repositoryIds.size
var promoted = 0
var stepCount = 0
var retryCount = 0
process@while (true) {
stepCount++
if (stepCount > 200) {
error("Too much steps. stepCount=$stepCount")
}
repo@for (repositoryId in repositoryIds.toList()) {
val state = try {
getRepositoryState(repositoryId)
} catch (e: SimpleHttpException) {
when (e.responseCode) {
404 -> {
println("Can't find $repositoryId anymore. Probably released. Stopping")
repositoryIds.remove(repositoryId)
continue@repo
}
else -> throw e
}
}
when {
state.transitioning -> {
println("Waiting transition $state")
}
// Even if open, if there are notifications we should drop it
state.notifications > 0 -> {
println("Dropping release because of error state.notifications=$state")
println(" - activity: " + getRepositoryActivity(repositoryId))
repositoryDrop(repositoryId)
repositoryIds.remove(repositoryId)
}
state.isOpen -> {
println("Closing open repository $state")
println(" - activity: " + getRepositoryActivity(repositoryId))
repositoryClose(repositoryId)
}
else -> {
println("Promoting repository $state")
println(" - activity: " + getRepositoryActivity(repositoryId))
repositoryPromote(repositoryId)
promoted++
}
}
}
if (repositoryIds.isEmpty()) {
println("Completed promoted=$promoted, totalRepositories=$totalRepositories, retryCount=$retryCount")
break@process
}
Thread.sleep(30_000L)
}
return promoted == totalRepositories
}
private val client get() = SimpleHttpClient(user, pass)
fun getRepositoryState(repositoryId: String): RepoState {
val info = client.requestWithRetry("${BASE}/repository/$repositoryId")
//println("info: ${info.toStringPretty()}")
return RepoState(
repositoryId = repositoryId,
type = info["type"].asString,
notifications = info["notifications"].asInt,
transitioning = info["transitioning"].asBoolean,
)
}
fun getRepositoryActivity(repositoryId: String): String {
val info = client.requestWithRetry("${BASE}/repository/$repositoryId/activity")
//println("info: ${info.toStringPretty()}")
return info.toStringPretty()
}
data class RepoState(
val repositoryId: String,
// "open" or "closed"
val type: String,
val notifications: Int,
val transitioning: Boolean
) {
val isOpen get() = type == "open"
}
private fun getDataMapForRepository(repositoryId: String): Map<String, Map<*, *>> {
return mapOf(
"data" to mapOf(
"stagedRepositoryIds" to listOf(repositoryId),
"description" to "",
"autoDropAfterRelease" to true,
)
)
}
fun repositoryClose(repositoryId: String) {
client.requestWithRetry("${BASE}/bulk/close", getDataMapForRepository(repositoryId))
}
fun repositoryPromote(repositoryId: String) {
client.requestWithRetry("${BASE}/bulk/promote", getDataMapForRepository(repositoryId))
}
fun repositoryDrop(repositoryId: String) {
client.requestWithRetry("${BASE}/bulk/drop", getDataMapForRepository(repositoryId))
}
fun findProfileRepositories(profileId: String): List<String> {
return client.requestWithRetry("${BASE}/profile_repositories")["data"].list
.filter { it["profileId"].asString == profileId }
.map { it["repositoryId"].asString }
}
fun findProfileIdByGroupId(groupId: String): String {
val profiles = client.requestWithRetry("$BASE/profiles")["data"].list
return profiles
.filter { groupId.startsWith(it["name"].asString) }
.map { it["id"].asString }
.firstOrNull() ?: error("Can't find profile with group id '$groupId'")
}
fun startStagedRepository(profileId: String): String {
return client.requestWithRetry("${BASE}/profiles/$profileId/start", mapOf(
"data" to mapOf("description" to "Explicitly created by easy-kotlin-mpp-gradle-plugin")
))["data"]["stagedRepositoryId"].asString
}
operator fun JsonElement.get(key: String): JsonElement = asJsonObject.get(key)
val JsonElement.list: JsonArray get() = asJsonArray
fun JsonElement.toStringPretty() = GsonBuilder().setPrettyPrinting().create().toJson(this)
}
open class SimpleHttpClient(
val user: String? = null,
val pass: String? = null
) {
open fun requestWithRetry(url: String, body: Any? = null, nretries: Int = 15): JsonElement {
var retryCount = 0
while (true) {
try {
return request(url, body)
} catch (e: SimpleHttpException) {
when (e.responseCode) {
in 500..599 -> { // Sometimes HTTP Error 502 Bad Gateway
e.printStackTrace()
retryCount++
if (retryCount >= nretries) throw RuntimeException("Couldn't access $url after $nretries retries :: ${e.responseCode} : ${e.message}", e)
println("Retrying... retryCount=$retryCount/$nretries")
Thread.sleep(15_000L + (retryCount * 5_000L))
continue
}
else -> {
throw e
}
}
}
}
}
open fun request(url: String, body: Any? = null): JsonElement {
val post = (URL(url).openConnection()) as HttpURLConnection
post.connectTimeout = 300 * 1000 // 300 seconds // 5 minutes
post.readTimeout = 300 * 1000 // 300 seconds // 5 minutes
post.requestMethod = (if (body != null) "POST" else "GET")
if (user != null && pass != null) {
val authBasic = Base64.getEncoder().encodeToString("${user}:${pass}".toByteArray(Charsets.UTF_8))
post.setRequestProperty("Authorization", "Basic $authBasic")
}
post.setRequestProperty("Accept", "application/json")
if (body != null) {
post.doOutput = true
post.setRequestProperty("Content-Type", "application/json")
val bodyText = if (body is String) body.toString() else JsonOutput.toJson(body)
//println(bodyText)
post.outputStream.write(bodyText.toByteArray(Charsets.UTF_8))
}
val postRC = post.responseCode
val postMessage = post.responseMessage
//println(postRC)
if (postRC < 400) {
return JsonParser.parseString(post.inputStream.reader(Charsets.UTF_8).readText())
} else {
val errorString = try {
post.errorStream?.reader(Charsets.UTF_8)?.readText()
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
null
}
throw SimpleHttpException(postRC, postMessage, url, errorString)
}
}
}
class SimpleHttpException(val responseCode: Int, val responseMessage: String, val url: String, val errorString: String?) :
RuntimeException("HTTP Error $responseCode $responseMessage - $url - $errorString")
object GithubCI {
fun setOutput(name: String, value: String) {
val GITHUB_OUTPUT = System.getenv("GITHUB_OUTPUT")
if (GITHUB_OUTPUT != null) {
File(GITHUB_OUTPUT).appendText("$name=$value\n")
} else {
println("::set-output name=$name::$value")
}
}
}
/*
rootProject.plugins.withType<org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin> {
rootProject.the<org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension>().apply{
this.nodeVersion = "20.12.2"
//download = false
}
}
*/
// Tiny, coupled and limited variant of amper compatible with the current structure, so we can bump to Kotlin 2.0.0 in the meantime, while amper is discarded or evolved.
class MicroAmper(val project: Project) {
private var kotlinPlatforms = mutableListOf<String>()
private var kotlinAliases = LinkedHashMap<String, List<String>>()
private var deps = mutableListOf<Dep>()
//val kotlinBasePlatforms by lazy { kotlinPlatforms.groupBy { getKotlinBasePlatform(it) }.filter { it.value != listOf(it.key) } }
val kotlinBasePlatforms by lazy { kotlinPlatforms.groupBy { getKotlinBasePlatform(it) } }
fun getKotlinBasePlatform(platform: String): String = platform.removeSuffix("X64").removeSuffix("X86").removeSuffix("Arm64").removeSuffix("Arm32").removeSuffix("Simulator").removeSuffix("Device").also {
check(it.all { it.isLowerCase() && !it.isDigit() })
}
data class Dep(val path: String, val exported: Boolean, val test: Boolean, val platform: String) {
val rplatform = platform.takeIf { it.isNotEmpty() } ?: "common"
val configuration = "$rplatform${if (test) "Test" else "Main"}${if (exported) "Api" else "Implementation"}"
}
fun parseFile(file: File, lines: List<String> = file.readLines()) {
var mode = ""
for (line in lines) {
val tline = line.substringBeforeLast('#').trim().takeIf { it.isNotEmpty() } ?: continue
if (line.startsWith(" ") || line.startsWith("\t") || line.startsWith("-")) {
when {
mode == "product" -> {
//println("product=$tline")
when {
tline.startsWith("platforms:") -> {
val platforms = tline.substringAfter('[').substringBeforeLast(']').split(',').map { it.trim() }
kotlinPlatforms.addAll(platforms)
}
}
}
mode == "aliases" -> {
//println("aliases=$tline")
if (tline.startsWith("-")) {
val (alias2, platforms2) = tline.split(":", limit = 2)
val alias = alias2.trim('-', ' ')
val platforms = platforms2.trim('[', ']', ' ').split(',').map { it.trim() }
//println(" -> alias=$alias, platforms=$platforms")
kotlinAliases[alias] = platforms
}
}
mode.contains("dependencies") -> {
val platform = mode.substringAfterLast('@', "")
val test = mode.startsWith("test")
val exported = line.contains(Regex(":\\s*exported"))
val path = tline.removePrefix("-").removeSuffix(": exported").removeSuffix(":exported").trim()
deps += Dep(path = path, exported = exported, test = test, platform = platform)
}
}
} else {
if (tline.endsWith(":")) {
mode = tline.trimEnd(':').trim()
}
if (tline.startsWith("apply:")) {
val paths = tline.substringAfter(':').trim('[', ',', ' ', ']').split(",")
for (path in paths) {
parseFile(file.parentFile.resolve(path))
}
//parseFile(File(project.rootDir, "common.module-template.yaml"))
}
}
}
}
data class SourceSetPair(val main: KotlinSourceSet, val test: KotlinSourceSet) {
fun dependsOn(other: SourceSetPair) {
main.dependsOn(other.main)
test.dependsOn(other.test)
}
}
val sourceSetPairs = LinkedHashMap<String, SourceSetPair>()
// specific depends on more generic
fun NamedDomainObjectContainer<KotlinSourceSet>.ssDependsOn(base: String, other: String) {
if (base == other) return
//println("$base dependsOn $other")
ssPair(base).dependsOn(ssPair(other))
}
val projectFiles: Set<String> = (project.projectDir.list() ?: emptyArray()).toSet()
fun SourceDirectorySet.srcDirIfExists(path: String) {
//if (path in projectFiles) setSrcDirs(listOf(path)) //else println("file doesn't exist $path")
//srcDir(path)
setSrcDirs(listOf(path))
}
fun NamedDomainObjectContainer<KotlinSourceSet>.ssPair(name: String): SourceSetPair {
return sourceSetPairs.getOrPut(name) {
val atName = if (name == "common") "" else "@$name"
SourceSetPair(
main = maybeCreate("${name}Main").also {
it.kotlin.srcDirIfExists("src$atName")
it.resources.srcDirIfExists("resources$atName")
it.kotlin.srcDir("build/generated/ksp/$name/${name}Main/kotlin")
},
test = maybeCreate("${name}Test").also {
it.kotlin.srcDirIfExists("test$atName")
it.resources.srcDirIfExists("testResources$atName")
it.kotlin.srcDir("build/generated/ksp/$name/${name}Test/kotlin")
}
)
}
}
fun applyTo() = with(project) {
project.kotlin.sourceSets {
ssDependsOn("native", "common")
ssDependsOn("posix", "native")
ssDependsOn("apple", "posix")
ssDependsOn("appleNonWatchos", "apple")
ssDependsOn("appleIosTvos", "apple")