Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert gradle ant java task to kotlin

I have a gradle ant task that starts a H2 database. The build script looks like this:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    runtime 'com.h2database:h2:1.3.168'
}

task startH2Db {
    group = 'database'
    description='Starts the H2 TCP database server on port 9092 and web admin on port 8082'
    doLast{
        ant.java( fork:true, spawn:true, classname:'org.h2.tools.Server', dir:projectDir){
            arg(value: "-tcp")
            arg(value: "-web")
            arg(value: "-tcpPort")
            arg(value: "9092")
            arg(value: "-webPort")
            arg(value: "8082")
            arg(value: "-webAllowOthers")
            classpath {
                pathelement(path:"${sourceSets.main.runtimeClasspath.asPath}")
            }
        }
    }
}

Given that Gradle are now supporting Kotlin, I decided to try and convert this build.gradle into a build.gradle.ktsfile.

I'm struggling to find documentation on how to do this in Kotlin. I've found examples of other ant tasks, but nothing with args like above. I have got as far as this:

plugins {
    java
}

repositories {
    mavenCentral()
}

dependencies {
    runtime ("com.h2database:h2:1.3.168")
}

tasks {
    register("startH2Database") {
        group = "database"
        description = "Starts the H2 TCP database server on port 9092 and web admin on port 8082"
        doLast {
            ant.withGroovyBuilder {
            "java"("fork" to true, "spawn" to true, "classname" to "org.h2.tools.Server", "dir" to projectDir)
            }
        }
    }
}

How do I configure the args and the classpath? Is there any extra documentation other than what's listed here: https://docs.gradle.org/current/userguide/ant.html?

like image 848
Ben Green Avatar asked Sep 03 '25 17:09

Ben Green


1 Answers

You may check more examples in the Gradle Kotlin DSL repository, e.g. https://github.com/gradle/kotlin-dsl/blob/master/samples/ant/build.gradle.kts

So your Ant call may look like

ant.withGroovyBuilder {
  "java"( 
     "fork" to true, 
     "spawn" to true, 
     "classname" to "org.h2.tools.Server", 
     "dir" to projectDir
   ){
      "arg"("value" to "-tcp")
      "arg"("value" to "-web")
      "arg"("value" to "-tcpPort")
      "arg"("value" to "9092")
      "arg"("value" to "-webPort")
      "arg"("value" to "8082")
      "arg"("value" to "-webAllowOthers")
      "classpath" {
        "pathelement"(
                "path" to configurations["runtime"].asPath
            )
      }
   }
}
like image 74
Eugene Petrenko Avatar answered Sep 06 '25 22:09

Eugene Petrenko