首页 > 解决方案 > Gradle kotlin dsl - how to specify duplicate tasks?

问题描述

The last comment in https://github.com/johnrengelman/shadow/issues/138 has an example of defining multiple shadowJars. I've tried without success to come up with a version that worked in kotlin DSL. What should it look like?

My latest attempt (of several) is the following, but it doesn't work because I'm not allowed to instantiate tasks directly. (I am new to gradle, so probably I'm missing something conceptually.)

tasks {
    val internal = ShadowJar()
    internal.isZip64 = true
    internal.archiveFileName.set("internal.jar")
    internal.mergeServiceFiles()
    internal.manifest {
        attributes(mapOf("Main-Class" to "com.foo.InternalApplication"))
    }
    internal.minimize()

    val external = ShadowJar()
    external.isZip64 = true
    external.archiveFileName.set("external.jar")
    external.mergeServiceFiles()
    external.manifest {
        attributes(mapOf("Main-Class" to "com.foo.ExternalApplication"))
    }
    external.minimize()
}

tasks {
    val internal by existing
    val external by existing

    "build" {
        dependsOn(internal)
        dependsOn(external)
    }
}

标签: gradlegradle-kotlin-dsl

解决方案


您是否尝试过定义扩展ShadowJar任务类型的新任务?

像这样的东西:

tasks.create<ShadowJar>("internal") {
    isZip64 = true
    archiveFileName.set("internal.jar")
    mergeServiceFiles()
    manifest {
        attributes(mapOf("Main-Class" to "com.foo.InternalApplication"))
    }
    minimize()
}

tasks.create<ShadowJar>("external") {
    isZip64 = true
    archiveFileName.set("external.jar")
    mergeServiceFiles()
    manifest {
        attributes(mapOf("Main-Class" to "com.foo.ExternalApplication"))
    }
    minimize()
}

构建任务应该已经存在。所以我们不想定义一个名称冲突的新任务,所以让我们配置现有build任务来添加新的依赖项,这样每次构建都会发生不和谐。

tasks.build {
    dependsOn("internal")
    dependsOn("external")
}

相反,如果您不想在每次构建项目时都生成 jars(会很多),那么您可能想要定义一个任务来显式调用 jar 两者。

tasks.create<Exec>("buildJars") {
    dependsOn("internal")
    dependsOn("external")
}

我不在可以对此进行测试的计算机上,因此我根据您的原始代码片段做出了很多假设。然而,这种方法是创建新任务并定义其类型的标准且正确的方法。

您可以在官方文档中阅读更多相关信息。所有代码片段都有一个选项卡可以在 Groovy 和 Kotlin 之间切换。


推荐阅读