如果你的目标是抑制废弃警告,以便可以使每个其他Kotlin警告都构建失败,那么这是我的经验。
有一种方法可以配置Kotlin编译器,使其在每个警告上都失败。只需将以下配置添加到您的build.gradle文件中:
android {
kotlinOptions {
allWarningsAsErrors = true
}
}
compileKotlin {
kotlinOptions {
allWarningsAsErrors = true
}
}
启用 allWarningsAsErrors
标志后,Kotlin 编译器会在每次使用弃用代码后失败。不幸的是,Kotlin 不支持忽略那些已弃用的警告或避免在这些警告上失败。
下面的 Gradle 脚本提供了解决此问题的方法。
import org.gradle.api.Project
import org.gradle.api.internal.GradleInternal
import org.gradle.configurationcache.extensions.serviceOf
import org.gradle.internal.logging.events.operations.LogEventBuildOperationProgressDetails
import org.gradle.internal.operations.BuildOperationDescriptor
import org.gradle.internal.operations.BuildOperationListener
import org.gradle.internal.operations.BuildOperationListenerManager
import org.gradle.internal.operations.OperationFinishEvent
import org.gradle.internal.operations.OperationIdentifier
import org.gradle.internal.operations.OperationProgressEvent
import org.gradle.internal.operations.OperationStartEvent
val kotlinWarnings = mutableListOf<String>()
val buildOperationListener = object : BuildOperationListener {
override fun started(buildOperation: BuildOperationDescriptor, startEvent: OperationStartEvent) {
}
override fun progress(operationIdentifier: OperationIdentifier, progressEvent: OperationProgressEvent) {
val log = progressEvent.details
if (log is LogEventBuildOperationProgressDetails) {
if (log.message.contains("w:") && !log.message.contains("is deprecated.") && !kotlinWarnings.contains(log.message)) {
kotlinWarnings.add(log.message)
}
}
}
override fun finished(buildOperation: BuildOperationDescriptor, finishEvent: OperationFinishEvent) {
}
}
val gradleInternal = project.gradle as GradleInternal
val buildOperationListenerManager = gradleInternal.serviceOf() as BuildOperationListenerManager?
buildOperationListenerManager?.addListener(buildOperationListener)
project.gradle.buildFinished {
buildOperationListenerManager?.removeListener(buildOperationListener)
if (kotlinWarnings.isNotEmpty()) {
kotlinWarnings.forEach { project.logger.warn(it) }
throw RuntimeException("Kotlin warning found")
}
}
BuildOperationListener
是添加到Gradle构建中的监听器,因此您可以监听每个控制台日志。检查每个日志以搜索Kotlin警告,但忽略弃用用法的警告。如果项目中存在Kotlin警告,则最终会抛出异常。
以下文章提供有关此主题的更多信息:在Kotlin警告时构建失败
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions.freeCompilerArgs += ["--Xjavac-arguments=-Xlint:-deprecation"] }
,参见 https://github.com/Kotlin/kotlinx.coroutines/issues/859 - Akash Shah@Suppress("DEPRECATION")
。 - andreoss