kotlingradlegradle-kotlin-dslgradle-task

Configure Gradle to work like a script or batch file


I have a Kotlin program that looks like this:

fun main(args: Array<String>) = runBlocking {
    if(args.first() == "deploy") {
        // do deployment
    }
}

Putting aside the obvious null-pointer issue for the moment, if I want to run this via Gradle I would have to enter this at the command-line...

gradle run --args="deploy"

... which is really verbose and cludgy. What I really want to be able to do is to issue a command like this and have it do the same thing:

gradle deploy

I don't really want to write a script or a batch file as these tend to be OS-specific and I feel like Gradle might be powerful enough to provide a solution. On that note however, I have been trawling through Gradle documentation and keep disappearing down rabbit holes wrt Tasks etc, hence my question here.


Solution

  • Assuming you are using the Kotlin JVM plugin, you can add the task you need in Kotlin DSL by writing:

    tasks.register<JavaExec>("deploy") {
        classpath = files(
            kotlin.target.compilations.named(SourceSet.MAIN_SOURCE_SET_NAME).map {
                it.output.allOutputs + it.runtimeDependencyFiles
            }
        )
        // For a main() function in src/main/kotlin/package/of/main/Main.kt
        mainClass = "package.of.main.MainKt"
        args("deploy")
    }
    

    The task type used here, JavaExec, can be further configured if you want to make more technical adjustments.