Add example scripting hosts with tests:

the simple scripting host and the one with maven resolving
This commit is contained in:
Ilya Chernikov
2018-02-05 16:00:59 +01:00
parent c48a74b84a
commit 3732422e6a
14 changed files with 319 additions and 1 deletions
@@ -0,0 +1 @@
import org.jetbrains.kotlin.gradle.dsl.Coroutines
@@ -0,0 +1,111 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.resolve.maven
import org.jetbrains.kotlin.script.util.*
import org.jetbrains.kotlin.script.util.impl.getResourcePathForClass
import java.io.File
import kotlin.reflect.KClass
import kotlin.script.dependencies.ScriptContents
import kotlin.script.dependencies.ScriptDependenciesResolver
import kotlin.script.experimental.api.*
import kotlin.script.experimental.definitions.ScriptDefinitionFromAnnotatedBaseClass
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.*
import kotlin.script.experimental.jvmhost.impl.KJVMCompilerImpl
val stdlibFile: File by lazy {
KotlinJars.stdlib
?: throw Exception("Unable to find kotlin stdlib, please specify it explicitly via \"kotlin.java.stdlib.jar\" property")
}
val selfFile: File by lazy {
getResourcePathForClass(MyScriptWithMavenDeps::class.java).takeIf(File::exists)
?: throw Exception("Unable to get path to the script base")
}
val scriptUtilsJarFile: File by lazy {
getResourcePathForClass(DependsOn::class.java).takeIf(File::exists)
?: throw Exception("Unable to get path to the kotlin-script-util.jar")
}
class MyConfigurator(val baseClass: KClass<Any>? = null) : ScriptConfigurator {
private val resolver = FilesAndMavenResolver()
override suspend fun baseConfiguration(scriptSource: ScriptSource?) : ResultWithDiagnostics<ScriptCompileConfiguration> =
myJvmConfig(scriptSource.toConfigEntry()).asSuccess()
override suspend fun refineConfiguration(
configuration: ScriptCompileConfiguration,
processedScriptData: ProcessedScriptData
): ResultWithDiagnostics<ScriptCompileConfiguration> {
val annotations = processedScriptData.getOrNull(ProcessedScriptDataParams.annotations)?.toList()?.takeIf { it.isNotEmpty() }
?: return configuration.asSuccess()
val scriptContents = object : ScriptContents {
override val annotations: Iterable<Annotation> = annotations
override val file: File? = null
override val text: CharSequence? = null
}
val diagnostics = arrayListOf<ScriptDiagnostic>()
fun report(severity: ScriptDependenciesResolver.ReportSeverity, message: String, position: ScriptContents.Position?) {
diagnostics.add(ScriptDiagnostic(message, mapLegacyDiagnosticSeverity(severity), mapLegacyScriptPosition(position)))
}
return try {
val newDepsFromResolver = resolver.resolve(scriptContents, emptyMap(), ::report, null).get()
?: return configuration.asSuccess(diagnostics)
val resolvedClasspath = newDepsFromResolver.classpath.toList().takeIf { it.isNotEmpty() }
?: return configuration.asSuccess(diagnostics)
val newDependency = JvmDependency(resolvedClasspath)
val updatedDeps =
configuration.getOrNull(ScriptCompileConfigurationParams.dependencies)?.plus(newDependency) ?: listOf(newDependency)
configuration.cloneWith(ScriptCompileConfigurationParams.dependencies to updatedDeps).asSuccess(diagnostics)
} catch (e: Throwable) {
ResultWithDiagnostics.Failure(*diagnostics.toTypedArray(), e.asDiagnostics())
}
}
}
fun myJvmConfig(vararg params: Pair<TypedKey<*>, Any?>): ScriptCompileConfiguration =
jvmConfigWithJavaHome(
ScriptCompileConfigurationParams.scriptSignature to ScriptSignature(MyScriptWithMavenDeps::class, ProvidedDeclarations()),
ScriptCompileConfigurationParams.importedPackages to listOf(DependsOn::class.qualifiedName!!, Repository::class.qualifiedName!!),
ScriptCompileConfigurationParams.dependencies to listOf(
JvmDependency(listOf(stdlibFile)),
JvmDependency(listOf(selfFile)),
JvmDependency(listOf(scriptUtilsJarFile))
),
ScriptCompileConfigurationParams.updateConfigurationOnAnnotations to listOf(DependsOn::class, Repository::class),
*params
)
fun evalFile(scriptFile: File): ResultWithDiagnostics<EvaluationResult> {
val scriptCompiler = JvmScriptCompiler(KJVMCompilerImpl(), DummyCompiledJvmScriptCache())
val scriptDefinition = ScriptDefinitionFromAnnotatedBaseClass(MyScriptWithMavenDeps::class)
val host = JvmBasicScriptingHost(
scriptDefinition.configurator,
scriptCompiler,
scriptDefinition.runner
)
return host.eval(myJvmConfig(scriptFile.toScriptSource().toConfigEntry()), ScriptEvaluationEnvironment())
}
fun main(vararg args: String) {
if (args.size != 1) {
println("usage: <app> <script file>")
} else {
val scriptFile = File(args[0])
println("Executing script $scriptFile")
val res = evalFile(scriptFile)
res.reports.forEach {
println(" : ${it.message}" + if (it.exception == null) "" else ": ${it.exception}")
}
}
}
@@ -0,0 +1,19 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.resolve.maven
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.basic.DefaultScriptSelector
import kotlin.script.experimental.jvm.runners.BasicJvmScriptRunner
@KotlinScript(
DefaultScriptSelector::class,
MyConfigurator::class,
BasicJvmScriptRunner::class
)
abstract class MyScriptWithMavenDeps {
// abstract fun body(vararg args: String): Int
}
@@ -0,0 +1,47 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.resolve.maven.test
import org.jetbrains.kotlin.script.examples.jvm.resolve.maven.evalFile
import org.junit.Assert
import org.junit.Test
import java.io.File
import kotlin.script.experimental.api.ResultWithDiagnostics
class ResolveTest {
@Test
fun testResolveJunit() {
val res = evalFile(File("testData/hello-maven-resolve-junit.kts"))
Assert.assertTrue(
"test failed:\n ${res.reports.joinToString("\n ") { it.message + if (it.exception == null) "" else ": ${it.exception}" }}",
res is ResultWithDiagnostics.Success
)
}
@Test
fun testUnresolvedJunit() {
val res = evalFile(File("testData/hello-unresolved-junit.kts"))
Assert.assertTrue(
"test failed - expecting a failure with the message \"Unresolved reference: junit\" but received " +
(if (res is ResultWithDiagnostics.Failure) "failure" else "success") +
":\n ${res.reports.joinToString("\n ") { it.message + if (it.exception == null) "" else ": ${it.exception}" }}",
res is ResultWithDiagnostics.Failure && res.reports.any { it.message.contains("Unresolved reference: junit") })
}
@Test
fun testResolveError() {
val res = evalFile(File("testData/hello-maven-resolve-error.kts"))
Assert.assertTrue(
"test failed - expecting a failure with the message \"Unknown set of arguments to maven resolver: abracadabra\" but received " +
(if (res is ResultWithDiagnostics.Failure) "failure" else "success") +
":\n ${res.reports.joinToString("\n ") { it.message + if (it.exception == null) "" else ": ${it.exception}" }}",
res is ResultWithDiagnostics.Failure && res.reports.any { it.message.contains("Unknown set of arguments to maven resolver: abracadabra") })
}
}
@@ -0,0 +1,5 @@
@file:DependsOn("abracadabra")
println("Hello, World!")
@@ -0,0 +1,7 @@
@file:DependsOn("junit:junit:4.11")
org.junit.Assert.assertTrue(true)
println("Hello, World!")
@@ -0,0 +1,5 @@
org.junit.Assert.assertTrue(true)
println("Hello, World!")
@@ -0,0 +1 @@
import org.jetbrains.kotlin.gradle.dsl.Coroutines
@@ -0,0 +1,64 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.simple
import org.jetbrains.kotlin.script.util.KotlinJars
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import kotlin.script.experimental.api.*
import kotlin.script.experimental.definitions.ScriptDefinitionFromAnnotatedBaseClass
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.*
import kotlin.script.experimental.jvmhost.impl.KJVMCompilerImpl
val stdlibFile: File by lazy {
KotlinJars.stdlib
?: throw Exception("Unable to find kotlin stdlib, please specify it explicitly via \"kotlin.java.stdlib.jar\" property")
}
val selfFile: File by lazy {
PathUtil.getResourcePathForClass(MyScript::class.java).takeIf(File::exists)
?: throw Exception("Unable to get path to the script base")
}
fun myJvmConfig(vararg params: Pair<TypedKey<*>, Any?>): ScriptCompileConfiguration =
jvmConfigWithJavaHome(
ScriptCompileConfigurationParams.scriptSignature to ScriptSignature(MyScript::class, ProvidedDeclarations.Empty),
ScriptCompileConfigurationParams.dependencies to listOf(
JvmDependency(listOf(stdlibFile)),
JvmDependency(listOf(selfFile))
),
*params
)
fun evalFile(scriptFile: File): ResultWithDiagnostics<EvaluationResult> {
val scriptCompiler = JvmScriptCompiler(KJVMCompilerImpl(), DummyCompiledJvmScriptCache())
val scriptDefinition = ScriptDefinitionFromAnnotatedBaseClass(MyScript::class)
val host = JvmBasicScriptingHost(
scriptDefinition.configurator,
scriptCompiler,
scriptDefinition.runner
)
return host.eval(myJvmConfig(scriptFile.toScriptSource().toConfigEntry()), ScriptEvaluationEnvironment())
}
fun main(vararg args: String) {
if (args.size != 1) {
println("usage: <app> <script file>")
} else {
val scriptFile = File(args[0])
println("Executing script $scriptFile")
val res = evalFile(scriptFile)
res.reports.forEach {
println(" : ${it.message}" + if (it.exception == null) "" else ": ${it.exception}")
}
}
}
@@ -0,0 +1,16 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.simple
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.basic.DefaultScriptSelector
import kotlin.script.experimental.basic.PassThroughConfigurator
import kotlin.script.experimental.jvm.runners.BasicJvmScriptRunner
@KotlinScript(DefaultScriptSelector::class, PassThroughConfigurator::class, BasicJvmScriptRunner::class)
abstract class MyScript {
// abstract fun body(vararg args: String): Int
}
@@ -0,0 +1,36 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.simple.test
import org.jetbrains.kotlin.script.examples.jvm.simple.evalFile
import org.junit.Assert
import java.io.File
import org.junit.Test
import kotlin.script.experimental.api.ResultWithDiagnostics
class SimpleTest {
@Test
fun testSimple() {
val res = evalFile(File("testData/hello.kts"))
Assert.assertTrue(
"test failed:\n ${res.reports.joinToString("\n ") { it.message + if (it.exception == null) "" else ": ${it.exception}" }}",
res is ResultWithDiagnostics.Success
)
}
@Test
fun testError() {
val res = evalFile(File("testData/error.kts"))
Assert.assertTrue(
"test failed - expecting a failure with the message \"Unresolved reference: abracadabra\" but received " +
(if (res is ResultWithDiagnostics.Failure) "failure" else "success") +
":\n ${res.reports.joinToString("\n ") { it.message + if (it.exception == null) "" else ": ${it.exception}" }}",
res is ResultWithDiagnostics.Failure && res.reports.any { it.message.contains("Unresolved reference: abracadabra") })
}
}
@@ -0,0 +1,3 @@
abracadabra("Hello, World!")
@@ -0,0 +1,3 @@
println("Hello, World!")