如果你的目标是禁止弃用,这样你就可以让构建在彼此的Kotlin警告上失败,那么这就是我的经验。
有一种方法可以配置 Kotlin 编译器,使其在每次警告时都失败。只需将以下配置添加到您的文件中:build.gradle
// For Android Project
android {
kotlinOptions {
allWarningsAsErrors = true
}
}
// For non Android Project
compileKotlin {
kotlinOptions {
allWarningsAsErrors = true
}
}
但是在启用该标志后,Kotlin 编译器在每次弃用的代码用法后都将失败。不幸的是,Kotlin 不支持忽略那些已弃用的警告或避免失败。allWarningsAsErrors
以下 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")
}
}
基本上,a 被添加到 Gradle 版本中,因此您可以侦听每个控制台日志。检查每个日志以搜索 Kotlin 警告,但忽略已弃用的使用警告。最后,如果项目上有 Kotlin 警告,则会引发异常BuildOperationListener
以下文章提供了有关此主题的详细信息:在 Kotlin 上构建失败警告