Gradle项目中的典型Kotlin构型非常简单,我正在寻找一种将其抽象为外部构建脚本的方法,以便可以重用它。
我有一个可行的解决方案(下面),但这感觉有点像一个黑客,因为kotlin插件并不是以这种方式发挥作用的。
当您使用无法按id应用插件时,从外部脚本中应用任何非标准插件是很麻烦的。
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.所以我设法破解了一个插件(只是实插件的一个修改版本),这迫使它从当前的构建脚本中找到插件。
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时,我都不太希望合并到插件的更改中。
发布于 2016-08-24 12:22:33
看看星云-科特林-插件。它似乎非常接近于你想要达到的目标。
发布于 2018-10-19 23:54:56
这里的问题是,有一个已知gradle虫关于不能从init脚本中应用id插件。这就是为什么您需要使用完全限定的类名作为解决方案。
例如,我在init脚本中有以下内容,它可以工作:
apply plugin: org.jetbrains.kotlin.gradle.plugin.KotlinPlatformJvmPlugin顺便说一句,我创建了一个gradle插件,用于准备带有init脚本- 自定义分级区中定义的通用设置的定制gradle发行版。它非常适合我的项目,例如,库项目的build.gradle如下所示(这是一个完整的文件,所有存储库、应用插件、依赖项等都是在init脚本中定义的):
dependencies {
compile 'org.springframework.kafka:spring-kafka'
}https://stackoverflow.com/questions/39117820
复制相似问题