[英]How to parse and modify build.gradle.kts Kotlin Gradle build script?
我想解析一个build.gradle.kts
(Kotlin 中的 Gradle 构建脚本),所以我可以找出当前设置了哪些值,并且我还想在某些类别中修改或添加新条目。
示例(build.gradle.kts):
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.2.6.RELEASE"
kotlin("jvm") version "1.3.71"
etc...
}
group = "net.myProject"
version = "1.0"
java.sourceCompatibility = JavaVersion.VERSION_11
val developmentOnly by configurations.creating
configurations {
runtimeClasspath {
extendsFrom(developmentOnly)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
etc...
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
它基本上是一个经典的 Spring 引导应用程序。 我希望能够做的是:
获取文件的某种结构化表示
所以我可以 append 一个固定版本到一个依赖项(例如implementation("org.springframework.boot:spring-boot-starter-actuator :2.2.6.RELEASE ")
所以我可以 append 新的依赖项进入依赖项列表
我知道这是 Gradle 构建脚本的特殊 DSL,但我在哪里可以找到它以及如何解析/使用它?
谢谢!
不幸的是 kotlin 似乎没有提供它自己的解析器,这意味着不会有一个简单的答案,你必须处理语言更新。 您可能还需要确保解析的结构允许您保留空格以保持格式不变。
ktlint可能是一个有趣的起点。 它使用 IntelliJ 的 PSI-Elements 并重用 IntelliJ 的解析器。
val normalizedText = text.replace("\r\n", "\n").replace("\r", "\n")
val positionByOffset = calculateLineColByOffset(normalizedText)
val fileName = if (script) "file.kts" else "file.kt"
val psiFile = psiFileFactory.createFileFromText(fileName, KotlinLanguage.INSTANCE, normalizedText) as KtFile
val errorElement = psiFile.findErrorElement()
if (errorElement != null) {
val (line, col) = positionByOffset(errorElement.textOffset)
throw ParseException(line, col, errorElement.errorDescription)
}
val rootNode = psiFile.node
// use visitor pattern on rootNode
坦率地说,除非这会给您的项目带来很多价值,否则我会尝试寻找不同的解决方案。 也许您可以从 json 文件等易于解析的源中读取build.gradle.kts
中的值?
希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.