Search code examples
gradlebuild.gradlegradle-kotlin-dsl

How to modify source code using task in build.gradle.kts?


I have a script that can print when necessary line is found in generated source code, but I have to remove those lines as well, I am wondering how can I do that? This task seems to be working for groovy but only prints found values for 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")
}


Solution

  • I was able to modify the content doing the following:

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