首页 > 解决方案 > 如何使用 build.gradle.kts 中的任务修改源代码?

问题描述

我有一个脚本可以在生成的源代码中找到必要的行时打印,但我也必须删除这些行,我想知道我该怎么做?此任务似乎适用于 groovy,但仅打印为 Kotlin 找到的值。

tasks.register<Copy>("filter") {
    from("src/generate-swagger/java") {
        filter { line ->
            if (line.contains("com.magazine.report.exception")) {
                println("found import")
                return@filter null
            }
            if (line.contains("throw new ReportException")) {
                println("found exception")
                return@filter line.replace("throw new ReportException", "throw new RuntimeException")
            }
            return@filter line
        }
    }
    into("generated/java")
    dependsOn("generate")
}

标签: gradlebuild.gradlegradle-kotlin-dsl

解决方案


我能够通过以下方式修改内容:

tasks.register<Copy>("filter") {
    from("src/generate-swagger/java") {
        filter { line ->
            if (line.contains("com.magazine.report.exception")) {
                return@filter ""
            }
            if (line.contains("throw new ReportException")) {
                return@filter line.replace("throw new ReportException", "throw new RuntimeException")
            }
            return@filter line
        }
    }
    into("generated/java")
    dependsOn("generate")
}

推荐阅读