The 典型的 Kotlin 配置 https://kotlinlang.org/docs/reference/using-gradle.htmlGradle 项目中的代码非常样板,我正在寻找一种将其抽象为外部构建脚本的方法,以便可以重用它。
我有一个可行的解决方案(如下),但感觉有点像黑客,因为 kotlin-gradle-plugin 不能以这种方式开箱即用。
当您从外部脚本应用任何非标准插件时,这是很混乱的无法通过id应用插件 https://discuss.gradle.org/t/how-do-i-apply-a-plugin-to-a-project-from-a-shared-applied-gradle-file/7508, i.e.
apply plugin: 'kotlin'
将导致Plugin with id 'kotlin' not found.
简单(通常)的解决方法是通过插件的完全限定类名来应用,即
apply plugin: org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper
在这种情况下会抛出一个很好的小异常,表明该插件可能不应该这样调用:
Failed to determine source cofiguration of kotlin plugin.
Can not download core. Please verify that this or any parent project
contains 'kotlin-gradle-plugin' in buildscript's classpath configuration.
所以我设法拼凑了一个插件(只是一个修改版本真正的插件 https://github.com/JetBrains/kotlin/blob/v1.0.3/libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinPluginWrapper.kt)这迫使它从当前的构建脚本中查找插件。
kotlin.gradle
buildscript {
ext.kotlin_version = "1.0.3"
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}
apply plugin: CustomKotlinPlugin
import org.jetbrains.kotlin.gradle.plugin.CleanUpBuildListener
import org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper
import org.jetbrains.kotlin.gradle.plugin.KotlinPlugin
import org.jetbrains.kotlin.gradle.tasks.KotlinTasksProvider
/**
* Wrapper around the Kotlin plugin wrapper (this code is largely a refactoring of KotlinBasePluginWrapper).
* This is required because the default behaviour expects the kotlin plugin to be applied from the project,
* not from an external buildscript.
*/
class CustomKotlinPlugin extends KotlinBasePluginWrapper {
@Override
void apply(Project project) {
// use String literal as KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY constant isn't available
System.setProperty("kotlin.environment.keepalive", "true")
// just use the kotlin version defined in this script
project.extensions.extraProperties?.set("kotlin.gradle.plugin.version", project.property('kotlin_version'))
// get the plugin using the current buildscript
def plugin = getPlugin(this.class.classLoader, project.buildscript)
plugin.apply(project)
def cleanUpBuildListener = new CleanUpBuildListener(this.class.classLoader, project)
cleanUpBuildListener.buildStarted()
project.gradle.addBuildListener(cleanUpBuildListener)
}
@Override
Plugin<Project> getPlugin(ClassLoader pluginClassLoader, ScriptHandler scriptHandler){
return new KotlinPlugin(scriptHandler, new KotlinTasksProvider(pluginClassLoader));
}
}
然后可以将其应用于任何项目(即apply from: "kotlin.gradle"
)然后您就可以开始进行 Kotlin 开发了。
它有效,而且我还没有遇到任何问题,但我想知道是否有更好的方法?我不太热衷于每次有新版本的 Kotlin 时都合并对插件的更改。