1

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.

1
  • 1
    By the way, you can have suspend fun main instead of runBlocking. Commented Jun 21, 2024 at 16:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.