【问题标题】:How to parse and modify build.gradle.kts Kotlin Gradle build script?如何解析和修改 build.gradle.kts Kotlin Gradle 构建脚本?
【发布时间】:2020-04-20 13:25:37
【问题描述】:

我想解析一个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 Boot 应用程序。我想做的是:

  1. 获取文件的某种结构化表示

  2. 所以我可以将固定版本附加到依赖项(例如 implementation("org.springframework.boot:spring-boot-starter-actuator :2.2.6.RELEASE ")

  3. 所以我可以将新的依赖项添加到依赖项列表中

我知道这是 Gradle 构建脚本的特殊 DSL,但我在哪里可以找到它以及如何解析/使用它?

谢谢!

【问题讨论】:

    标签: spring parsing kotlin gradle gradle-kotlin-dsl


    【解决方案1】:

    不幸的是,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 中的值?

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 2017-06-07
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多