Skip to content

Instantly share code, notes, and snippets.

@bamboo
Last active May 11, 2020 11:25
Show Gist options
  • Save bamboo/f29e738c2a17a36e87c814b7452afe31 to your computer and use it in GitHub Desktop.
Save bamboo/f29e738c2a17a36e87c814b7452afe31 to your computer and use it in GitHub Desktop.
Drive kotlinc from build.gradle
// Execute Kotlin script with:
//
// gradle -q foo
//
// For correctness, we're going to configure two independent classpath configurations, one for kotlinc and the other for the
// script(s) we want to execute.
configurations {
kotlinc
scripts
}
ext.kotlinVersion = "1.1.0-rc-91"
repositories {
maven { url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' }
jcenter()
}
def kotlinModule(String name) {
"org.jetbrains.kotlin:kotlin-$name:$kotlinVersion"
}
dependencies {
kotlinc(kotlinModule("compiler"))
kotlinc(kotlinModule("stdlib"))
kotlinc(kotlinModule("runtime"))
kotlinc(kotlinModule("reflect"))
kotlinc(kotlinModule("script-runtime"))
// Our simple script depends only on the stdlib but additional dependencies could be
// added to this configuration.
scripts(kotlinModule("stdlib"))
}
def kotlinHome = file("$buildDir/kotlin")
task prepareKotlinHome(type: Copy) {
from(configurations.kotlinc)
into("$kotlinHome/lib")
rename {
// strip the version suffix to satisfy the compiler
(it - "-${kotlinVersion}.jar") + ".jar"
}
}
task foo(type: JavaExec) {
group "My"
description "Executes foo.kts"
dependsOn prepareKotlinHome
main = "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler"
classpath = configurations.kotlinc
args(
"-kotlin-home", kotlinHome,
"-classpath", configurations.scripts.asPath,
"-script", "foo.kts")
}
println("Hello from Kotlin script!")
@abelkov
Copy link

abelkov commented Apr 24, 2020

Here are the updated dependencies for Kotlin 1.3.72:

dependencies {
    kotlinc(kotlinModule("stdlib"))
    kotlinc(kotlinModule("reflect"))
    kotlinc(kotlinModule("compiler-embeddable"))
    kotlinc(kotlinModule("scripting-compiler-embeddable"))

    scripts(kotlinModule("stdlib"))
}

@PrzemyslawSwiderski
Copy link

How would this build script looked in Kotlin DSL?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment