JetBrains Space Help

Run Kotlin Code

As the Automation DSL is based on Kotlin, you can run any Kotlin code inside job steps. In case of a container, you should put your code inside the kotlinScript block. For example:

job("build and publish") { container("gradle:6.1.1-jre11") { kotlinScript { api -> api.gradle("build") try { api.gradle("publish") } catch (ex: Exception) { println("Publishing failed") } } } }

How it works under the hood (with some simplification): Space compiles the script into a .jar file and runs it with a command like java -jar script.jar. This means that the image you use to run the script must include JRE/JDK (version 9 or later).

APIs for working with Space modules and external tools

In the kotlinScript block, you have access to various APIs: Space module APIs and APIs for various external tools (Gradle, dotnet, and others).

job("build and publish") { container("gradle") { kotlinScript { api -> try { api.gradle("build") } catch (ex: Exception) { val recipient = MessageRecipient.Channel(ChatChannel.FromName("CI-channel")) val content = ChatMessage.Text("Build failed") api.space().chats.messages.sendMessage(recipient, content) } } } }

In this example, we use api.gradle to run Gradle commands and api.space().chats to access the Chats module. For the full list of APIs, refer to job.container.kotlinScript.

Using external packages in kotlinScript

Kotlin script lets you use functions from external packages. To do this, you should reference the required package with the @file:DependsOn("$package_name") annotation. The $package_name is the name of the package available on Maven Central.

For example, the following script gets a random joke from icanhazdadjoke.com using the OkHttp client and prints it to the job log.

@file:DependsOn("com.squareup.okhttp:okhttp:2.7.4", "org.json:json:20200518") import com.squareup.okhttp.* import org.json.JSONObject job("Get random joke") { container("openjdk:11") { kotlinScript { val client = OkHttpClient() val request = Request.Builder() .url("http://icanhazdadjoke.com") .addHeader("Accept", "application/json") .build() val response = client.newCall(request).execute() val jData = response.body().string() val jObject = JSONObject(jData) val joke = jObject.get("joke").toString() println(joke) } } }
Last modified: 18 February 2021