[build] Fully support Android target; Update to Gradle 8.0

This commit is contained in:
Him188
2023-04-17 11:40:28 +01:00
parent fc549d380f
commit 164f621427
39 changed files with 534 additions and 589 deletions

View File

@@ -70,6 +70,10 @@ dependencies {
exclude("org.jetbrains.kotlin", "kotlin-stdlib-common")
}
// https://mvnrepository.com/artifact/com.android.library/com.android.library.gradle.plugin
api("com.android.library:com.android.library.gradle.plugin:${version("androidGradlePlugin")}")
api("com.google.code.gson:gson:2.10.1")
api("gradle.plugin.com.google.gradle:osdetector-gradle-plugin:1.7.0")
api(gradleApi())

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019-2022 Mamoe Technologies and contributors.
* Copyright 2019-2023 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
@@ -52,7 +52,8 @@ object BinaryCompatibilityConfigurator {
}
}
private fun Project.getValidatorDir(dir: File) = ":validator" + project.path + ":${dir.name}"
// Also change: settings.gradle.kts:116
private fun Project.getValidatorDir(dir: File) = ":validator" + project.path + "-validator:${dir.name}"
private fun File.writeTextIfNeeded(text: String) {
if (!this.exists()) return this.writeText(text)
@@ -81,7 +82,13 @@ object BinaryCompatibilityConfigurator {
if (targetName == null) {
tasks.findByName("apiBuild")?.dependsOn(project.tasks.getByName("jar"))
} else {
tasks.findByName("apiBuild")?.dependsOn(project.tasks.getByName("${targetName}Jar"))
tasks.findByName("apiBuild")?.dependsOn(
if (targetName.contains("android")) {
project.tasks.getByName("bundleDebugAar")
} else {
project.tasks.getByName("${targetName}Jar")
}
)
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019-2022 Mamoe Technologies and contributors.
* Copyright 2019-2023 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
@@ -70,7 +70,6 @@ object DependencyDumper {
val outFile = temporaryDir.resolve(out)
outputs.file(outFile)
val conf = project.configurations.getByName(confName)
dependsOn(conf)
doLast {
outFile.parentFile.mkdirs()

View File

@@ -7,9 +7,14 @@
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
@file:Suppress("UNUSED_VARIABLE")
import com.android.build.api.dsl.LibraryExtension
import com.google.gradle.osdetector.OsDetector
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.attributes.Attribute
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getting
import org.gradle.kotlin.dsl.withType
@@ -23,6 +28,7 @@ import org.jetbrains.kotlin.gradle.plugin.KotlinTargetPreset
import org.jetbrains.kotlin.gradle.plugin.mpp.*
import org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink
import java.io.File
import java.util.*
val MIRAI_PLATFORM_ATTRIBUTE = Attribute.of(
"net.mamoe.mirai.platform", String::class.java
@@ -37,7 +43,7 @@ val MIRAI_PLATFORM_INTERMEDIATE = Attribute.of(
val IDEA_ACTIVE = System.getProperty("idea.active") == "true" && System.getProperty("publication.test") != "true"
val OS_NAME = System.getProperty("os.name").toLowerCase()
val OS_NAME = System.getProperty("os.name").lowercase()
lateinit var osDetector: OsDetector
@@ -162,7 +168,7 @@ fun Project.configureJvmTargetsHierarchical() {
compilations.all {
this.compileTaskProvider.configure { // IDE complain
enabled = false
}
}
}
attributes.attribute(KotlinPlatformType.attribute, KotlinPlatformType.common) // magic
attributes.attribute(MIRAI_PLATFORM_ATTRIBUTE, "jvmBase") // avoid resolution
@@ -183,16 +189,47 @@ fun Project.configureJvmTargetsHierarchical() {
if (isTargetEnabled("android")) {
if (isAndroidSDKAvailable) {
jvm("android") {
attributes.attribute(KotlinPlatformType.attribute, KotlinPlatformType.androidJvm)
// apply(plugin = "com.android.library")
android {
if (IDEA_ACTIVE) {
attributes.attribute(MIRAI_PLATFORM_ATTRIBUTE, "android") // avoid resolution
}
}
configureAndroidTarget()
val androidMain by sourceSets.getting
val androidTest by sourceSets.getting
androidMain.dependsOn(jvmBaseMain)
androidTest.dependsOn(jvmBaseTest)
for (s in arrayOf("androidMain")) {
sourceSets.all { if (name in s) dependsOn(jvmBaseMain) }
}
// this can cause problems on sync
// for (s in arrayOf("androidDebug", "androidRelease")) {
// sourceSets.all { if (name in s) dependsOn(androidMain) }
// }
val androidUnitTest by sourceSets.getting {
dependsOn(jvmBaseTest)
}
// for (s in arrayOf("androidUnitTestDebug", "androidUnitTestRelease")) {
// sourceSets.all { if (name in s) dependsOn(androidUnitTest) }
// }
val androidInstrumentedTest by sourceSets.getting {
dependsOn(jvmBaseTest)
}
// for (s in arrayOf("androidInstrumentedTestDebug")) {
// sourceSets.all { if (name in s) dependsOn(androidInstrumentedTest) }
// }
// afterEvaluate {
//// > androidDebug dependsOn commonMain
//// androidInstrumentedTest dependsOn jvmBaseTest
//// androidInstrumentedTestDebug dependsOn
//// androidMain dependsOn commonMain, jvmBaseMain
//// androidRelease dependsOn commonMain
//// androidUnitTest dependsOn commonTest, jvmBaseTest
//// androidUnitTestDebug dependsOn commonTest
//// androidUnitTestRelease dependsOn commonTest
// error(this@apply.sourceSets.joinToString("\n") {
// it.name + " dependsOn " + it.dependsOn.joinToString { it.name }
// })
// }
} else {
printAndroidNotInstalled()
}
@@ -210,6 +247,41 @@ fun Project.configureJvmTargetsHierarchical() {
}
}
@Suppress("UnstableApiUsage")
fun Project.configureAndroidTarget() {
extensions.getByType(KotlinMultiplatformExtension::class.java).apply {
// trick
this.sourceSets.apply {
removeIf { it.name == "androidAndroidTestRelease" }
removeIf { it.name == "androidTestFixtures" }
removeIf { it.name == "androidTestFixturesDebug" }
removeIf { it.name == "androidTestFixturesRelease" }
}
}
extensions.getByType(LibraryExtension::class.java).apply {
compileSdk = 33
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdk = rootProject.extra["mirai.android.target.api.level"]!!.toString().toInt()
targetSdk = 33
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
buildTypes.getByName("release") {
isMinifyEnabled = true
isShrinkResources = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
)
}
}
}
/**
* ```
* common
@@ -235,13 +307,14 @@ fun KotlinMultiplatformExtension.configureNativeTargetsHierarchical(
val nativeMainSets = mutableListOf<KotlinSourceSet>()
val nativeTestSets = mutableListOf<KotlinSourceSet>()
val nativeTargets = mutableListOf<KotlinTarget>() // actually KotlinNativeTarget, but KotlinNativeTarget is an internal API (complained by IDEA)
val nativeTargets =
mutableListOf<KotlinTarget>() // actually KotlinNativeTarget, but KotlinNativeTarget is an internal API (complained by IDEA)
fun KotlinMultiplatformExtension.addNativeTarget(
preset: KotlinTargetPreset<*>,
): KotlinTarget {
val target = targetFromPreset(preset, preset.name)
val target = targetFromPreset(preset, preset.name)
nativeMainSets.add(target.compilations[MAIN_COMPILATION_NAME].kotlinSourceSets.first())
nativeTestSets.add(target.compilations[TEST_COMPILATION_NAME].kotlinSourceSets.first())
nativeTargets.add(target)
@@ -387,10 +460,10 @@ fun KotlinMultiplatformExtension.configureNativeTargetBinaries(project: Project)
val target = targets.getByName(targetName) as KotlinNativeTarget
target.binaries {
sharedLib(listOf(NativeBuildType.DEBUG, NativeBuildType.RELEASE)) {
baseName = project.name.toLowerCase().replace("-", "")
baseName = project.name.lowercase(Locale.ROOT).replace("-", "")
}
staticLib(listOf(NativeBuildType.DEBUG, NativeBuildType.RELEASE)) {
baseName = project.name.toLowerCase().replace("-", "")
baseName = project.name.lowercase(Locale.ROOT).replace("-", "")
}
}
}

View File

@@ -7,32 +7,23 @@
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
@file:Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
import org.gradle.api.JavaVersion
import org.gradle.api.NamedDomainObjectCollection
import org.gradle.api.NamedDomainObjectList
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.testing.Test
import org.gradle.kotlin.dsl.*
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension
import org.jetbrains.kotlin.gradle.dsl.KotlinSingleTargetExtension
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.KotlinTarget
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
fun Project.useIr() {
kotlinCompilations?.forEach { kotlinCompilation ->
kotlinCompilation.kotlinOptions.freeCompilerArgs += "-Xuse-ir"
}
}
private fun Project.jvmVersion(): JavaVersion {
return if (project.path.endsWith("mirai-console-intellij")) {
JavaVersion.VERSION_17
@@ -94,22 +85,16 @@ fun Project.preConfigureJvmTarget() {
fun Project.configureJvmTarget() {
val defaultVer = jvmVersion()
configure(kotlinSourceSets.orEmpty()) {
languageSettings {
optIn("net.mamoe.mirai.utils.TestOnly")
optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
}
}
extensions.findByType(JavaPluginExtension::class.java)?.run {
sourceCompatibility = defaultVer
targetCompatibility = defaultVer
}
kotlinTargets.orEmpty().filterIsInstance<KotlinJvmTarget>().forEach { target ->
when (target.attributes.getAttribute(KotlinPlatformType.attribute)) { // mirai does magic, don't use target.platformType
allKotlinTargets().all {
if (this !is KotlinJvmTarget) return@all
when (this.attributes.getAttribute(KotlinPlatformType.attribute)) { // mirai does magic, don't use target.platformType
KotlinPlatformType.androidJvm -> {
target.compilations.all {
this.compilations.all {
/*
* Kotlin JVM compiler generates Long.hashCode witch is available since API 26 when targeting JVM 1.8 while IR prefer member function hashCode always.
*/
@@ -122,7 +107,7 @@ fun Project.configureJvmTarget() {
else -> {
}
}
target.testRuns["test"].executionTask.configure { useJUnitPlatform() }
this.testRuns["test"].executionTask.configure { useJUnitPlatform() }
}
}
@@ -148,7 +133,8 @@ fun Project.configureKotlinTestSettings() {
}
isKotlinMpp -> {
kotlinSourceSets?.forEach { sourceSet ->
kotlinSourceSets?.all {
val sourceSet = this
fun configureJvmTest(sourceSet: KotlinSourceSet) {
sourceSet.dependencies {
implementation(kotlin("test-junit5"))?.because(b)
@@ -158,12 +144,14 @@ fun Project.configureKotlinTestSettings() {
}
}
val target = kotlinTargets.orEmpty()
val target = allKotlinTargets()
.find { it.name == sourceSet.name.substringBeforeLast("Main").substringBeforeLast("Test") }
when {
sourceSet.name == "commonTest" -> {
if (isJvmLikePlatform(target)) {
if (target?.platformType == KotlinPlatformType.jvm &&
target.attributes.getAttribute(MIRAI_PLATFORM_INTERMEDIATE) != true
) {
configureJvmTest(sourceSet)
} else {
sourceSet.dependencies {
@@ -174,7 +162,9 @@ fun Project.configureKotlinTestSettings() {
}
sourceSet.name.contains("test", ignoreCase = true) -> {
if (isJvmLikePlatform(target)) {
if (target?.platformType == KotlinPlatformType.jvm &&
target.attributes.getAttribute(MIRAI_PLATFORM_INTERMEDIATE) != true
) {
configureJvmTest(sourceSet)
}
}
@@ -191,7 +181,9 @@ val testExperimentalAnnotations = arrayOf(
"kotlin.ExperimentalUnsignedTypes",
"kotlin.time.ExperimentalTime",
"io.ktor.util.KtorExperimentalAPI",
"kotlin.io.path.ExperimentalPathApi"
"kotlin.io.path.ExperimentalPathApi",
"kotlinx.coroutines.ExperimentalCoroutinesApi",
"net.mamoe.mirai.utils.TestOnly",
)
val experimentalAnnotations = arrayOf(
@@ -217,11 +209,10 @@ val testLanguageFeatures = listOf(
"ContextReceivers"
)
fun Project.configureKotlinExperimentalUsages() {
fun Project.configureKotlinOptIns() {
val sourceSets = kotlinSourceSets ?: return
for (target in sourceSets) {
target.configureKotlinExperimentalUsages()
sourceSets.all {
configureKotlinOptIns()
}
for (name in testLanguageFeatures) {
@@ -233,7 +224,7 @@ fun Project.configureKotlinExperimentalUsages() {
}
}
fun KotlinSourceSet.configureKotlinExperimentalUsages() {
fun KotlinSourceSet.configureKotlinOptIns() {
languageSettings.progressiveMode = true
experimentalAnnotations.forEach { a ->
languageSettings.optIn(a)
@@ -278,13 +269,22 @@ inline fun <reified T> Any?.safeAs(): T? {
val Project.kotlinSourceSets get() = extensions.findByName("kotlin").safeAs<KotlinProjectExtension>()?.sourceSets
val Project.kotlinTargets
get() =
extensions.findByName("kotlin").safeAs<KotlinSingleTargetExtension<*>>()?.target?.let { listOf(it) }
?: extensions.findByName("kotlin").safeAs<KotlinMultiplatformExtension>()?.targets
fun Project.allKotlinTargets(): NamedDomainObjectCollection<KotlinTarget> {
return extensions.findByName("kotlin")?.safeAs<KotlinSingleTargetExtension<*>>()
?.target?.let { namedDomainObjectListOf(it) }
?: extensions.findByName("kotlin")?.safeAs<KotlinMultiplatformExtension>()?.targets
?: namedDomainObjectListOf()
}
private inline fun <reified T> Project.namedDomainObjectListOf(vararg values: T): NamedDomainObjectList<T> {
return objects.namedDomainObjectList(T::class.java).apply { addAll(values) }
}
val Project.isKotlinJvmProject: Boolean get() = extensions.findByName("kotlin") is KotlinJvmProjectExtension
val Project.isKotlinMpp: Boolean get() = extensions.findByName("kotlin") is KotlinMultiplatformExtension
val Project.kotlinCompilations
get() = kotlinTargets?.flatMap { it.compilations }
fun Project.allKotlinCompilations(action: (KotlinCompilation<KotlinCommonOptions>) -> Unit) {
allKotlinTargets().all {
compilations.all(action)
}
}

View File

@@ -98,6 +98,7 @@ fun KotlinDependencyHandler.relocateCompileOnly(
relocatedDependency: RelocatedDependency,
): ExternalModuleDependency {
val dependency = compileOnly(relocatedDependency.notation) {
relocatedDependency.exclusionAction(this)
}
project.relocationFilters.add(
RelocationFilter(
@@ -122,6 +123,7 @@ fun DependencyHandler.relocateCompileOnly(
): Dependency {
val dependency =
addDependencyTo(this, "compileOnly", relocatedDependency.notation, Action<ExternalModuleDependency> {
relocatedDependency.exclusionAction(this)
})
project.relocationFilters.add(
RelocationFilter(
@@ -145,7 +147,7 @@ fun KotlinDependencyHandler.relocateImplementation(
action: ExternalModuleDependency.() -> Unit = {}
): ExternalModuleDependency {
val dependency = implementation(relocatedDependency.notation) {
relocatedDependency.exclusionAction(this)
}
project.relocationFilters.add(
RelocationFilter(
@@ -181,6 +183,7 @@ fun DependencyHandler.relocateImplementation(
): ExternalModuleDependency {
val dependency =
addDependencyTo(this, "implementation", relocatedDependency.notation, Action<ExternalModuleDependency> {
relocatedDependency.exclusionAction(this)
})
project.relocationFilters.add(
RelocationFilter(

View File

@@ -55,13 +55,16 @@ fun Project.configureShadowDependenciesForPublishing() {
"configureShadowDependenciesForPublishing can only be used on root project."
}
val jarTaskNames = arrayOf("jvmJar", "jvmBaseJar")
gradle.projectsEvaluated {
// Tasks requested to run in this build
val allTasks = rootProject.allprojects.asSequence().flatMap { it.tasks }
val publishTasks = allTasks.filter { it.name.contains("publish", ignoreCase = true) }
val relocateTasks = allTasks.filter { it.name.contains("relocate", ignoreCase = true) }
val jarTasks = allTasks.filter { it.name.contains("jar", ignoreCase = true) }
val jarTasks = allTasks.filter {
it.name in jarTaskNames
}
val compileKotlinTasks = allTasks.filter { it.name.contains("compileKotlin", ignoreCase = true) }
val compileTestKotlinTasks = allTasks.filter { it.name.contains("compileTestKotlin", ignoreCase = true) }
@@ -99,7 +102,7 @@ private fun KotlinTarget.configureRelocationForMppTarget(project: Project) = pro
group = "mirai"
description = "Relocate dependencies to internal package"
destinationDirectory.set(buildDir.resolve("libs")) // build/libs
archiveBaseName.set("${project.name}-${targetName.toLowerCase()}") // e.g. "mirai-core-api-jvm"
archiveBaseName.set("${project.name}-${targetName.lowercase()}") // e.g. "mirai-core-api-jvm"
dependsOn(compilations["main"].compileTaskProvider) // e.g. compileKotlinJvm

View File

@@ -0,0 +1,10 @@
/*
* Copyright 2019-2023 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
fun String.capitalize(): String = this.replaceFirstChar { it.uppercaseChar() }

View File

@@ -56,7 +56,7 @@ object Versions {
const val dynamicDelegation = "0.4.0-180.1"
const val mavenCentralPublish = "1.0.0"
const val androidGradlePlugin = "4.1.1"
const val androidGradlePlugin = "7.3.1"
const val android = "4.1.1.4"
const val shadow = "8.1.0"
@@ -172,6 +172,7 @@ object ExcludeProperties {
val `kotlinx-coroutines` = multiplatformJvm(groupId = "org.jetbrains.kotlinx", "kotlinx-coroutines")
val `ktor-io` = multiplatformJvm(groupId = "io.ktor", "ktor-io")
val `everything from slf4j` = exclude(groupId = "org.slf4j", null)
val `slf4j-api` = exclude(groupId = "org.slf4j", "slf4j-api")
/**
* @see org.gradle.kotlin.dsl.exclude
@@ -192,6 +193,7 @@ object ExcludeProperties {
val `ktor-io` = ktor("io", Versions.ktor)
val `ktor-io_relocated` = RelocatedDependency(`ktor-io`, "io.ktor.utils.io") {
exclude(ExcludeProperties.`everything from slf4j`)
exclude(ExcludeProperties.`slf4j-api`)
}
val `ktor-http` = ktor("http", Versions.ktor)

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2019-2023 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
import org.jetbrains.kotlin.gradle.dsl.KotlinCompile
/*
* Copyright 2019-2023 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
private val EXPLICIT_API = "-Xexplicit-api=strict"
// Workaround for explicit API in androidMain
// https://youtrack.jetbrains.com/issue/KT-37652/Support-explicit-mode-for-Android-projects
// https://youtrack.jetbrains.com/issue/KT-37652/Support-explicit-mode-for-Android-projects#focus=Comments-27-4501224.0-0
project.tasks
.matching { it is KotlinCompile<*> && !it.name.contains("test", ignoreCase = true) }
.configureEach {
if (!project.hasProperty("kotlin.optOutExplicitApi")) {
val kotlinCompile = this as KotlinCompile<*>
if (EXPLICIT_API !in kotlinCompile.kotlinOptions.freeCompilerArgs) {
kotlinCompile.kotlinOptions.freeCompilerArgs += EXPLICIT_API
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019-2022 Mamoe Technologies and contributors.
* Copyright 2019-2023 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
@@ -34,7 +34,7 @@ fun ByteArray.toUHexString(
return buildString(length * 2) {
this@toUHexString.forEachIndexed { index, it ->
if (index in offset until lastIndex) {
var ret = it.toUByte().toString(16).toUpperCase()
var ret = it.toUByte().toString(16).uppercase()
if (ret.length == 1) ret = "0$ret"
append(ret)
if (index < lastIndex - 1) append(separator)