问题:如何在运行时执行一组 kotlin 文件并从中返回一个kts
文件的结果?
我编写系统,它能够执行kts
带有指令的文件。目前它支持以下执行模式:
main.kts
- 该文件将被执行。它应该返回List<Step>
但是,用户可以将任何其他文件放在同一文件夹中。例如,文件夹可以包含以下文件:
main.kts
Constants.kt
// 它有一些常量Helpers.kt
// 一些额外的方法
ScriptEngine具有评估代码的方法,但是它只有一个输入文件。
问题:如何要求 ScriptEngine 将类编译到类路径中,但只执行其中一个?
此解决方案不正确,因为文件顺序很重要(例如,如果第一个文件依赖于最后一个文件,则编译失败):
// there is security issue here
val classLoader = Thread.currentThread().contextClassLoader
val engineManager = ScriptEngineManager(classLoader)
setIdeaIoUseFallback()
val ktsEngine: ScriptEngine = engineManager.getEngineByExtension("kts")
/**
* There is issue here: if file1 requires file2 compilation then execution below fails.
*
* Right way: find the solution to compile whole folder and evaluate the single file.
*/
filesFromFolderExceptMain.forEach {
ktsEngine.eval(it)
}
return ktsEngine.eval(mainScriptFile) as List<Step>
另一种解决方案(可能导致不可预测的编译波动):
val context = filesFromFolderExceptMain.joinToString(System.lineSeparator()
ktsEngine.eval(context)
return ktsEngine.eval(mainScriptFile) as List<Step>
所以,问题:如何在运行时执行一组 kotlin 文件并kts
从它们返回一个文件的结果?