fridgepolice
fridgepolice

Reputation: 379

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

Upvotes: 2

Views: 724

Answers (1)

Julian
Julian

Reputation: 1675

Have you tried defining new tasks that extends the ShadowJar task type?

Something like this:

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

The build task should already exist. So we don't want to define a new task with a conflicting name, so let's instead configure the existing build task to add the new dependencies so jarring happens on every build.

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

If instead you don't want to produce jars every time your project builds (it'll be a lot), you might want to instead define a task to call explicitly to jar both.

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

I'm not on a computer where I can test this out, so I'm making quite a few assumptions based on your original code snippets. This approach, however, is a standard and correct way to create new tasks and define their type.

You can read more about that here at the official docs. All the code snippets have a tab to toggle between Groovy and Kotlin.

Upvotes: 3

Related Questions