Vampire
08/25/2020, 7:14 PM.kt
file with an object expression in it to the actual instance?
Like with using K2JVMCompiler
for example?
Are there any examples for that?Michael
08/25/2020, 8:03 PMVampire
08/25/2020, 8:27 PMHanno
08/25/2020, 8:32 PMHanno
08/25/2020, 8:33 PMVampire
08/25/2020, 9:53 PMK2JVMCompiler().run {
val args = K2JVMCompilerArguments().apply {
freeArgs = listOf(file("src/main/kotlin/net/kautler/dao/ResultSerializer.kt").absolutePath)
classpathAsList = sequenceOf(buildscript.classLoader, GroovyObject::class.java.classLoader)
.flatMap(ClassLoader::classPathFromTypicalResourceUrls)
.toList()
destinationAsFile = ...
noReflect = true
noStdlib = true
skipRuntimeVersionCheck = true
}
exec(
PrintingMessageCollector(System.out, WITHOUT_PATHS, true),
Services.EMPTY,
args
)
}
Now I just have to try to load and use it and then have to try whether I can leave out some of those compiler flags 🙂Hanno
08/25/2020, 10:06 PMVampire
08/25/2020, 10:07 PMVampire
08/25/2020, 10:56 PMURLClassLoader(
arrayOf(classesDir.toURI().toURL()),
buildscript.classLoader
)
.loadClass("net.kautler.dao.ResultSerializer")
.getField("INSTANCE")
.get(null)
.cast<KSerializer<Result>>()
.let { Json(Stable.copy(prettyPrint = true)).stringify(it, this) }
.also { reportFile.writeText(it) }
Vampire
08/25/2020, 11:22 PMVampire
08/27/2020, 3:55 PMBasicJvmScriptingHost
.
But using the compiler and evaluator directly worked even from a Gradle build script.
So what I have now is:
file("build/dependencyUpdates/report.json")
.apply { parentFile.mkdirs() }
.also { reportFile ->
val resultSerializer = resultSerializerByClassLoader ?: resultSerializerByScriptingHost
Json(Stable.copy(prettyPrint = true))
.stringify(resultSerializer, this)
.also { reportFile.writeText(it) }
}
/* ... */
@Suppress("UNCHECKED_CAST")
val resultSerializerByClassLoader
get() = layout
.buildDirectory
.dir("classes/kotlin/main")
.get()
.let { classesDir ->
if (!classesDir.file("net/kautler/dao/ResultSerializer.class").asFile.isFile) {
return@let null
}
URLClassLoader(
arrayOf(classesDir.asFile.toURI().toURL()),
buildscript.classLoader
)
.loadClass("net.kautler.dao.ResultSerializer")
.kotlin
.objectInstance
as KSerializer<Result>?
}
@Suppress("UNCHECKED_CAST")
val resultSerializerByScriptingHost
get() = runBlocking {
JvmScriptCompiler(defaultJvmScriptingHostConfiguration)(
"""
${file("src/main/kotlin/net/kautler/dao/ResultSerializer.kt").readText()}
ResultSerializer
""".toScriptSource(),
ScriptCompilationConfiguration {
jvm {
dependenciesFromCurrentContext(
"gradle-versions-plugin",
"kotlinx-serialization-runtime",
"groovy-all"
)
}
}
).onSuccess { BasicJvmScriptEvaluator()(it) }
}
.valueOrThrow()
.returnValue
.let { it as Value }
.value
as KSerializer<Result>
🙂Hanno
08/27/2020, 5:12 PMVampire
08/27/2020, 8:36 PM