如何跨多个Gradle项目共享样板Kotlin配置?

Jam*_*ett 4 gradle kotlin gradle-plugin

在典型的科特林配置在摇篮项目是非常的样板,我正在寻找抽象出来到外部构建脚本,以便它可以重复使用的方式.

我有一个工作的解决方案(下面),但感觉有点像黑客,因为kotlin-gradle-plugin不能以这种方式开箱即用.

从外部脚本应用任何非标准插件是很麻烦的,因为你不能通过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.
Run Code Online (Sandbox Code Playgroud)

所以我设法破解了一个插件(只是真正的插件的修改版本),迫使它从当前的buildcript中找到插件.

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,这可以应用于任何项目(即apply from: "kotlin.gradle"),并且您已经开始运行Kotlin开发.

它有效,我还没有任何问题,但我想知道是否有更好的方法?每当有新版本的Kotlin时,我并不是真的热衷于合并插件的更改.

小智 6

看看nebula-kotlin-plugin.它似乎非常接近你想要在那里实现的目标.