gpt4 book ai didi

gradle - 如何在多个 Gradle 项目之间共享样板 Kotlin 配置?

转载 作者:行者123 更新时间:2023-12-02 06:40:07 30 4
gpt4 key购买 nike

typical Kotlin configuration Gradle 项目中的代码非常样板,我正在寻找一种将其抽象为外部构建脚本的方法,以便可以重用它。

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

像您一样从外部脚本应用任何非标准插件是很困惑的 can't apply the plugin by id ,即

应用插件:'kotlin' 将导致 找不到 id 'kotlin' 的插件。

简单(通常)的解决方法是通过插件的完全限定类名来应用,即

应用插件: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.

所以我设法组合了一个插件(只是 real plugin 的修改版本),迫使它从当前构建脚本中查找插件。

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));
}
}

然后可以将其应用到任何项目中(即从“kotlin.gradle”应用),然后您就可以开始运行 Kotlin 开发了。

它有效,而且我还没有遇到任何问题,但我想知道是否有更好的方法?我并不热衷于每次有新版本的 Kotlin 时都合并对插件的更改。

最佳答案

查看 nebula-kotlin-plugin 。它似乎非常接近您想要实现的目标。

关于gradle - 如何在多个 Gradle 项目之间共享样板 Kotlin 配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39117820/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com