|
| 1 | +/* |
| 2 | + * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. |
| 3 | + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. |
| 4 | + */ |
| 5 | + |
| 6 | +package org.jetbrains.kotlin.script.examples.jvm.simple.host |
| 7 | + |
| 8 | +import org.jetbrains.kotlin.script.examples.jvm.simple.SimpleScript |
| 9 | +import java.io.File |
| 10 | +import kotlin.script.experimental.api.EvaluationResult |
| 11 | +import kotlin.script.experimental.api.ResultWithDiagnostics |
| 12 | +import kotlin.script.experimental.host.toScriptSource |
| 13 | +import kotlin.script.experimental.jvm.dependenciesFromClassloader |
| 14 | +import kotlin.script.experimental.jvm.dependenciesFromCurrentContext |
| 15 | +import kotlin.script.experimental.jvm.jvm |
| 16 | +import kotlin.script.experimental.jvm.updateClasspath |
| 17 | +import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost |
| 18 | +import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate |
| 19 | + |
| 20 | +fun evalFile(scriptFile: File): ResultWithDiagnostics<EvaluationResult> { |
| 21 | + val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<SimpleScript> { |
| 22 | + jvm { |
| 23 | + // configure dependencies for compilation, they should contain at least the script base class and |
| 24 | + // its dependencise |
| 25 | + // variant 1: try to extract current classpath and take only a path to the specified "script.jar" |
| 26 | + dependenciesFromCurrentContext( |
| 27 | + "script" /* script library jar name (exact or without a version) */ |
| 28 | + ) |
| 29 | + // variant 2: try to extract current classpath and use it for the compilation without filtering |
| 30 | +// dependenciesFromCurrentContext(wholeClasspath = true) |
| 31 | + // variant 3: try to extract a classpath from a particular classloader (or Thread.contextClassLoader by default) |
| 32 | + // filtering as in the variat 1 is supported too |
| 33 | +// dependenciesFromClassloader(classLoader = SimpleScript::class.java.classLoader, wholeClasspath = true) |
| 34 | + // variant 4: explicit classpath |
| 35 | +// updateClasspath(listOf(File("/path/to/jar"))) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return BasicJvmScriptingHost().eval(scriptFile.toScriptSource(), compilationConfiguration, null) |
| 40 | +} |
| 41 | + |
| 42 | +fun main(vararg args: String) { |
| 43 | + if (args.size != 1) { |
| 44 | + println("usage: <app> <script file>") |
| 45 | + } else { |
| 46 | + val scriptFile = File(args[0]) |
| 47 | + println("Executing script $scriptFile") |
| 48 | + |
| 49 | + val res = evalFile(scriptFile) |
| 50 | + |
| 51 | + res.reports.forEach { |
| 52 | + println(" : ${it.message}" + if (it.exception == null) "" else ": ${it.exception}") |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments