|
| 1 | +import java.io.File |
| 2 | +import kotlin.script.experimental.annotations.KotlinScript |
| 3 | +import kotlin.script.experimental.api.EvaluationResult |
| 4 | +import kotlin.script.experimental.api.ResultWithDiagnostics |
| 5 | +import kotlin.script.experimental.api.ScriptDiagnostic |
| 6 | +import kotlin.script.experimental.host.toScriptSource |
| 7 | +import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost |
| 8 | +import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate |
| 9 | +import kotlin.script.experimental.jvm.dependenciesFromCurrentContext |
| 10 | +import kotlin.script.experimental.jvm.jvm |
| 11 | + |
| 12 | +fun main(args: Array<String>) { |
| 13 | + println("Hello World!") |
| 14 | + |
| 15 | + // Try adding program arguments via Run/Debug configuration. |
| 16 | + // Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html. |
| 17 | + println("Program arguments: ${args.joinToString()}") |
| 18 | + |
| 19 | + if (args.isEmpty()) { |
| 20 | + val file = File("default.kts") |
| 21 | + |
| 22 | + println(file.absolutePath) |
| 23 | + |
| 24 | + val results = evalFile(File("default.kts")) |
| 25 | + |
| 26 | + results.reports.forEach { |
| 27 | + if (it.severity > ScriptDiagnostic.Severity.DEBUG) { |
| 28 | + println(" : ${it.message}" + if (it.exception == null) "" else ": ${it.exception}") |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | +} |
| 35 | + |
| 36 | +@KotlinScript(fileExtension = "simplescript.kts") |
| 37 | +abstract class SimpleScript |
| 38 | + |
| 39 | +fun evalFile(scriptFile: File): ResultWithDiagnostics<EvaluationResult> { |
| 40 | + val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<SimpleScript> { |
| 41 | + jvm { |
| 42 | + // configure dependencies for compilation, they should contain at least the script base class and |
| 43 | + // its dependencies |
| 44 | + // variant 1: try to extract current classpath and take only a path to the specified "script.jar" |
| 45 | +// dependenciesFromCurrentContext( |
| 46 | +// "script" /* script library jar name (exact or without a version) */ |
| 47 | +// ) |
| 48 | + // variant 2: try to extract current classpath and use it for the compilation without filtering |
| 49 | + dependenciesFromCurrentContext(wholeClasspath = true) |
| 50 | + // variant 3: try to extract a classpath from a particular classloader (or Thread.contextClassLoader by default) |
| 51 | + // filtering as in the variat 1 is supported too |
| 52 | +// dependenciesFromClassloader(classLoader = SimpleScript::class.java.classLoader, wholeClasspath = true) |
| 53 | + // variant 4: explicit classpath |
| 54 | +// updateClasspath(listOf(File("/path/to/jar"))) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return BasicJvmScriptingHost().eval(scriptFile.toScriptSource(), compilationConfiguration, null) |
| 59 | +} |
0 commit comments