'Execute .kts (kotlin script) from gradle

Scenario:

  • A gradle project, using the org.jetbrains.kotlin.jvm plugin
  • The project has some *.kts kotlin script files located inside src/main/kotlin. The scripts do various tasks, for instance there is a script for loading test data from a set of CSV files into a local H2 database, a script for creating a test user in the database etc.
  • I currently run these scripts using IntelliJ IDEA run configurations
  • The gradle build file is using kotlinscript (build.gradle.kts)

To make things easier to set up for new developers, I would like to configure gradle so I can run the scripts directly using gradle. That would simplify my README.md, instead of "use IntelliJ to execute the script xxx.kts with arguments yyy and zzz, then nnn.kts", I could write "execute gradle loadTestDataIntoLocalH2Database".

Questions/issues:

  • Is there a simple way to execute a *.kts script from gradle?


Solution 1:[1]

Puzzled my answer together from https://docs.gradle.org/current/userguide/plugins.html#sec:script_plugins , https://kotlinexpertise.com/execute-kotlin-scripts-with-gradle/ and https://stackoverflow.com/a/52139585/9936828

Although I didn't try it, the second link seems like the best solution if you are ok with adding the scripts to your projects package instead of keeping them as loose scripts.

Tested with gradle 7.2.

First option is the most straightforward with no changes to code, but requires you to install the kotlin compiler CLI (kotlinc), gradle can then call it to execute the scripts:

task<Exec>("MyTask") {
    commandLine("kotlinc", "-script", "foo.gradle.kts")
}

Then call it with gradle -q MyTask. Or obviously you could also provide the direct instructions to run kotlinc for the user without wrapping it in gradle.

Second option would be to load your script as a plugin. This however causes the kotlinscript annotations such as external imports (@file:Import, etc) to not work.

Wrap your code in your script in a task:

tasks.create("MyTask") {
    doLast {
        <do your stuff here>
    }
}

load as plugin in your build script:

apply(from = "foo.kts")

Then call it with gradle -q MyTask.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 somethingsomething