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(displayName = "Run publish script", image = "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).

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).

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

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

Using functions declared in external packages

kotlinScript 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 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(image = "openjdk:11") { kotlinScript { val client = OkHttpClient() val request = Request.Builder() .url("") .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: 22 March 2021