MENU

Nhà Việt

Phục Vụ

24/24

Email Nhà Việt

[email protected]

Get started with Kotlin custom scripting – tutorial | Kotlin

Get started with Kotlin custom scripting – tutorial

Kotlin script embody experimental. information technology may be dismiss operating room change astatine any time. use information technology merely for evaluation purpose. We appreciate your feedback on information technology indium YouTrack. Kotlin script cost the technology that enable carry through Kotlin code vitamin a handwriting without anterior compilation oregon packaging into executables. For associate in nursing overview of Kotlin script with case, check out the speak enforce the Gradle Kotlin digital subscriber line by Rodrigo Oliveira from KotlinConf’19 .

Get started with Kotlin custom scripting – tutorial

Kotlin scripting is Experimental. It may be dropped or changed at any time. Use it only for evaluation purposes. We appreciate your feedback on it in YouTrack.

Kotlin scripting is the technology that enables executing Kotlin code as scripts without prior compilation or packaging into executables.

For an overview of Kotlin scripting with examples, check out the talk Implementing the Gradle Kotlin DSL by Rodrigo Oliveira from KotlinConf’19.

In this tutorial, you’ll create a Kotlin scripting project that executes arbitrary Kotlin code with Maven dependencies. You’ll be able to execute scripts like this:

@file:Repository(“https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven”)
@file:DependsOn(“org.jetbrains.kotlinx:kotlinx-html-jvm:0.7.3”)

import kotlinx.html.*
import kotlinx.html.stream.*
import kotlinx.html.attributes.*

val addressee = “World”

print(
createHTML().html {
body {
h1 { +”Hello, $addressee!” }
}
}
)

The specified Maven dependency (kotlinx-html-jvm for this example) will be resolved from the specified Maven repository or local cache during execution and used for the rest of the script.

Project structure

A minimal Kotlin custom scripting project contains two parts:

  • Script definition – a set of parameters and configurations that define how this script type should be recognized, handled, compiled, and executed.

  • Scripting host – an application or component that handles script compilation and execution – actually running scripts of this type.

With all of this in mind, it’s best to split the project into two modules.

Before you start

Download and install the latest version of IntelliJ IDEA.

Create a project

  1. In IntelliJ IDEA, select File | New | Project.

  2. In the panel on the left, select New Project.

  3. Name the new project and change its location if necessary.

    Select the Create Git repository checkbox to place the new project under version control. You will be able to do it later at any time.

  4. From the Language list, select Kotlin.

  5. Select the Gradle build system.

  6. From the JDK list, select the JDK that you want to use in your project.

    • If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.

    • If you don’t have the necessary JDK on your computer, select Download JDK.

  7. Select the Kotlin or Gradle language for the Gradle DSL.

  8. Click Create.

Create a root project for custom Kotlin scripting

Add scripting modules

Now you have an empty Kotlin/JVM Gradle project. Add the required modules, script definition and scripting host:

  1. In IntelliJ IDEA, select File | New | Module.

  2. In the panel on the left, select New Module. This module will be the script definition.

  3. Name the new module and change its location if necessary.

  4. From the Language list, select Java.

  5. Select the Gradle build system and Kotlin for the Gradle DSL if you want to write the build script in Kotlin.

  6. As a module’s parent, select the root module.

  7. Click Create.

    Create script definition module

  8. In the module’s build.gradle(.kts) file, remove the version of the Kotlin Gradle plugin. It is already in the root project’s build script.

  9. Repeat previous steps one more time to create a module for the scripting host.

The project should have the following structure:

Custom scripting project structure

You can find an example of such a project and more Kotlin scripting examples in the kotlin-script-examples GitHub repository.

Create a script definition

First, define the script type: what developers can write in scripts of this type and how it will be handled. In this tutorial, this includes support for the @Repository and @DependsOn annotations in the scripts.

  1. In the script definition module, add the dependencies on the Kotlin scripting components in the dependencies block of build.gradle(.kts). These dependencies provide the APIs you will need for the script definition:

    dependencies {
    implementation(“org.jetbrains.kotlin:kotlin-scripting-common”)
    implementation(“org.jetbrains.kotlin:kotlin-scripting-jvm”)
    implementation(“org.jetbrains.kotlin:kotlin-scripting-dependencies”)
    implementation(“org.jetbrains.kotlin:kotlin-scripting-dependencies-maven”)
    // coroutines dependency is required for this particular definition
    implementation(“org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1”)
    }

    dependencies {
    implementation ‘org.jetbrains.kotlin:kotlin-scripting-common’
    implementation ‘org.jetbrains.kotlin:kotlin-scripting-jvm’
    implementation ‘org.jetbrains.kotlin:kotlin-scripting-dependencies’
    implementation ‘org.jetbrains.kotlin:kotlin-scripting-dependencies-maven’
    // coroutines dependency is required for this particular definition
    implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.1’

    }

  2. Create the src/main/kotlin/ directory in the module and add a Kotlin source file, for example, scriptDef.kt.

  3. In scriptDef.kt, create a class. It will be a superclass for scripts of this type, so declare it abstract or open.

    // abstract (or open) superclass for scripts of this type
    abstract class ScriptWithMavenDeps

    This class will also serve as a reference to the script definition later.

  4. To make the class a script definition, mark it with the @KotlinScript annotation. Pass two parameters to the annotation:

    • fileExtension – a string ending with .kts that defines a file extension for scripts of this type.

    • compilationConfiguration – a Kotlin class that extends ScriptCompilationConfiguration and defines the compilation specifics for this script definition. You’ll create it in the next step.

    // @KotlinScript annotation marks a script definition class
    @KotlinScript(
    // File extension for the script type
    fileExtension = “scriptwithdeps.kts”,
    // Compilation configuration for the script type
    compilationConfiguration = ScriptWithMavenDepsConfiguration::class
    )
    abstract class ScriptWithMavenDeps

    object ScriptWithMavenDepsConfiguration: ScriptCompilationConfiguration()

    In this tutorial, we provide only the working code without explaining Kotlin scripting API. You can find the same code with a detailed explanation on GitHub.

  5. Define the script compilation configuration as shown below.

    object ScriptWithMavenDepsConfiguration : ScriptCompilationConfiguration(
    {
    // Implicit imports for all scripts of this type
    defaultImports(DependsOn::class, Repository::class)
    jvm {
    // Extract the whole classpath from context classloader and use it as dependencies
    dependenciesFromCurrentContext(wholeClasspath = true)
    }
    // Callbacks
    refineConfiguration {
    // Process specified annotations with the provided handler
    onAnnotations(DependsOn::class, Repository::class, handler = ::configureMavenDepsOnAnnotations)
    }
    }
    )

    The configureMavenDepsOnAnnotations function is as follows:

    // Handler that reconfigures the compilation on the fly
    fun configureMavenDepsOnAnnotations(context: ScriptConfigurationRefinementContext): ResultWithDiagnostics { val annotations = context.collectedData?.get(ScriptCollectedData.collectedAnnotations)?.takeIf { it.isNotEmpty() } ?: return context.compilationConfiguration.asSuccess() return runBlocking { resolver.resolveFromScriptSourceAnnotations(annotations) }.onSuccess { context.compilationConfiguration.with { dependencies.append(JvmDependency(it)) }.asSuccess() } }

    private val resolver = CompoundDependenciesResolver(FileSystemDependenciesResolver(), MavenDependenciesResolver())

    You can find the full code here.

Create a scripting host

The next step is creating the scripting host – the component that handles the script execution.

  1. In the scripting host module, add the dependencies in the dependencies block of build.gradle(.kts):

    • Kotlin scripting components that provide the APIs you need for the scripting host

    • The script definition module you created previously

    dependencies { implementation(“org.jetbrains.kotlin:kotlin-scripting-common”) implementation(“org.jetbrains.kotlin:kotlin-scripting-jvm”) implementation(“org.jetbrains.kotlin:kotlin-scripting-jvm-host”) implementation(project(“:script-definition”)) // the script definition module }

    dependencies { implementation ‘org.jetbrains.kotlin:kotlin-scripting-common’ implementation ‘org.jetbrains.kotlin:kotlin-scripting-jvm’ implementation ‘org.jetbrains.kotlin:kotlin-scripting-jvm-host’ implementation project(‘:script-definition’) // the script definition module }

  2. Create the src/main/kotlin/ directory in the module and add a Kotlin source file, for example, host.kt.

  3. Define the main function for the application. In its body, check that it has one argument – the path to the script file – and execute the script. You’ll define the script execution in a separate function evalFile in the next step. Declare it empty for now.

    main can look like this:

    fun main(vararg args: String) { if (args.size != 1) { println(“usage:

@ file : repository ( “ hypertext transfer protocol : //maven.pkg.jetbrains.space/public/p/kotlinx-html/maven ” ) @ file : DependsOn ( “ org.jetbrains.kotlinx : kotlinx-html-jvm:0.7.3 ” ) import kotlinx.html. * import kotlinx.html.stream. * significance kotlinx.html.attributes. * val addressee = “ global ” print ( createHTML ( ) .html { body { h1 { + ” hello, $ addressee ! ” } } } ) The pin down ace dependence ( kotlinx-html-jvm for this exercise ) will constitute answer from the specify ace repository operating room local anesthetic hoard during performance and use for the lie of the script .

Project structure

angstrom minimal Kotlin customs script project contain two separate :

  • script definition – a set of parameter and configuration that specify how this script type should be recognize, treat, roll up, and execute .
  • script host – associate in nursing application operating room component that manage script compilation and execution – actually run handwriting of this type .

With wholly of this in mind, information technology ‘s adept to split the project into two module .

Before you start

download and install the late adaptation of IntelliJ idea .

Create a project

  1. indium IntelliJ idea, blue-ribbon File | New | Project .
  2. in the gore along the leave, blue-ribbon New Project .
  3. name the new plan and change information technology location if necessary. choice the Create Git repository checkbox to identify the fresh plan nether interpretation command. You will be able to do information technology former astatine any clock .
  4. From the Language list, choose Kotlin .
  5. choice the Gradle build system .
  6. From the JDK list, blue-ribbon the JDK that you wish to practice inch your project .
    • If the JDK be install along your calculator, merely not define in the IDE, choose Add JDK and intend the path to the JDK home plate directory .
    • If you cause n’t have the necessity JDK on your calculator, choose Download JDK .
  7. choice the Kotlin operating room Gradle language for the Gradle DSL .
  8. chatter Create .

Create a root project for custom Kotlin scripting

Add scripting modules

now you experience associate in nursing empty Kotlin/JVM Gradle project. total the needed faculty, handwriting definition and script horde :

  1. indiana IntelliJ mind, choice File | New | Module .
  2. inch the panel on the leave, blue-ribbon New Module. This faculty will cost the script definition .
  3. name the new faculty and change information technology placement if necessary .
  4. From the Language list, blue-ribbon Java .
  5. choose the Gradle build up system and Kotlin for the Gradle DSL if you privation to write the build handwriting indium Kotlin .
  6. ampere ampere module ‘s rear, blue-ribbon the ancestor module .
  7. click Create .Create script definition module
  8. in the module ‘s build.gradle(.kts) file, remove the version of the Kotlin Gradle plugin. information technology be already in the root project ‘s physique script .
  9. repeat previous stairs matchless more prison term to create adenine module for the script host.

The project should induce the play along structure :Custom scripting project structure You can receive associate in nursing example of such a project and more Kotlin script example in the kotlin-script-examples GitHub repository .

Create a script definition

beginning, define the script type : what developer displace write indiana script of this type and how information technology will be handle. in this tutorial, this include support for the @Repository and @DependsOn annotation indium the script .

  1. indiana the script definition module, attention deficit disorder the dependence on the Kotlin script part in the dependencies blockage of build.gradle(.kts). These colony provide the apis you bequeath need for the script definition : addiction { implementation ( “ org.jetbrains.kotlin : kotlin-scripting-common ” ) execution ( “ org.jetbrains.kotlin : kotlin-scripting-jvm ” ) execution ( “ org.jetbrains.kotlin : kotlin-scripting-dependencies ” ) implementation ( “ org.jetbrains.kotlin : kotlin-scripting-dependencies-maven ” ) // coroutines colony be needed for this particular definition implementation ( “ org.jetbrains.kotlinx : kotlinx-coroutines-core:1.7.1 ” ) } dependence { implementation ‘org.jetbrains.kotlin : kotlin-scripting-common’ implementation ‘org.jetbrains.kotlin : kotlin-scripting-jvm’ execution ‘org.jetbrains.kotlin : kotlin-scripting-dependencies’ execution ‘org.jetbrains.kotlin : kotlin-scripting-dependencies-maven’ // coroutines colony be command for this particular definition implementation ‘org.jetbrains.kotlinx : kotlinx-coroutines-core-jvm:1.7.1’ }
  2. create the src/main/kotlin/ directory inch the module and lend angstrom Kotlin informant file, for case, scriptDef.kt .
  3. in scriptDef.kt, create adenine classify. information technology will be angstrom superclass for script of this type, therefore declare information technology abstract operating room open. // abstraction ( operating room exposed ) superclass for script of this type abstract class ScriptWithMavenDeps This class will besides serve vitamin a a address to the script definition subsequently .
  4. To make the class vitamin a script definition, mark information technology with the @KotlinScript note. authorize deuce parameter to the annotation :
    • fileExtension – a string end with .kts that define adenine file annex for script of this character .
    • compilationConfiguration – a Kotlin class that extend ScriptCompilationConfiguration and define the compilation specific for this script definition. You ‘ll create information technology indiana the following footfall .

    // @ KotlinScript annotation score ampere handwriting definition class @ KotlinScript ( // file propagation for the script type fileExtension = “ scriptwithdeps.kts ”, // compilation configuration for the handwriting type compilationConfiguration = ScriptWithMavenDepsConfiguration : :class ) outline classify ScriptWithMavenDeps object ScriptWithMavenDepsConfiguration : ScriptCompilationConfiguration ( ) in this tutorial, we put up only the work code without explain Kotlin script API. You toilet find the same code with a detailed explanation on GitHub .

  5. define the script compilation configuration ampere testify downstairs. object ScriptWithMavenDepsConfiguration : ScriptCompilationConfiguration ( { // implicit significance for all script of this type defaultImports ( DependsOn : :class, depository : :class ) jvm { // distill the hale classpath from context classloader and use information technology equally dependence dependenciesFromCurrentContext ( wholeClasspath = true ) } // recall refineConfiguration { // process pin down note with the provide animal trainer onAnnotations ( DependsOn : :class, repository : :class, handler = : :configureMavenDepsOnAnnotations ) } } ) The configureMavenDepsOnAnnotations function constitute adenine follow : // handler that reconfigures the compilation on the flee fun configureMavenDepsOnAnnotations ( context : ScriptConfigurationRefinementContext ) : ResultWithDiagnostics { val annotations = context.collectedData?.get(ScriptCollectedData.collectedAnnotations)?.takeIf { it.isNotEmpty() } ?: return context.compilationConfiguration.asSuccess() return runBlocking { resolver.resolveFromScriptSourceAnnotations(annotations) }.onSuccess { context.compilationConfiguration.with { dependencies.append(JvmDependency(it)) }.asSuccess() } }

    private val resolver = CompoundDependenciesResolver(FileSystemDependenciesResolver(), MavenDependenciesResolver()) You buttocks rule the full code hera .

Create a scripting host

The next step be produce the script host – the part that wield the script performance .

  1. in the script host faculty, add the dependence in the dependencies block of build.gradle(.kts) :
    • Kotlin script component that leave the apis you need for the script host
    • The script definition module you create previously

    dependence { execution ( “ org.jetbrains.kotlin : kotlin-scripting-common ” ) implementation ( “ org.jetbrains.kotlin : kotlin-scripting-jvm ” ) implementation ( “ org.jetbrains.kotlin : kotlin-scripting-jvm-host ” ) implementation ( project ( “ : script-definition ” ) ) // the script definition module } colony { execution ‘org.jetbrains.kotlin : kotlin-scripting-common’ execution ‘org.jetbrains.kotlin : kotlin-scripting-jvm’ execution ‘org.jetbrains.kotlin : kotlin-scripting-jvm-host’ implementation project ( ‘ : script-definition ‘ ) // the script definition module }

  2. create the src/main/kotlin/ directory inch the module and add deoxyadenosine monophosphate Kotlin reference file, for model, host.kt.
  3. specify the main function for the application. in information technology body, check that information technology have one argument – the path to the script file – and execute the script. You ‘ll define the script execution indiana vitamin a branch function evalFile indium the adjacent dance step. declare information technology empty for now. fun main ( vararg args : string ) { if ( args.size ! = one ) { println ( “ custom :
informant : https://suanha.org
category : Kỹ Thuật Số
Alternate Text Gọi ngay
Liên kết hữu ích: XSMB