All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.metaeffekt.artifact.analysis.scripting.KotlinScripting.kt Maven / Gradle / Ivy

There is a newer version: 0.132.0
Show newest version
@file:JvmName("KotlinScripting")

package com.metaeffekt.artifact.analysis.scripting

import com.metaeffekt.artifact.analysis.scripting.config.inventory.InventoryFilterImplicitReceiver
import com.metaeffekt.artifact.analysis.scripting.config.inventory.InventoryFilterScript
import com.metaeffekt.artifact.analysis.scripting.config.inventory.Predicates
import com.metaeffekt.artifact.analysis.scripting.config.javabased.AnotherReceiver
import com.metaeffekt.artifact.analysis.scripting.config.javabased.JavaBasedScript
import org.metaeffekt.core.inventory.processor.reader.InventoryReader
import org.metaeffekt.core.inventory.processor.writer.InventoryWriter
import java.io.File
import java.util.function.Consumer
import kotlin.script.experimental.api.*
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate
import kotlin.script.experimental.jvmhost.createJvmEvaluationConfigurationFromTemplate


interface Diagnostics : Consumer

fun runInventoryFilterScriptWithDiagnostic(
    fileName: String,
    inventories: Map,
    diagnostics: Diagnostics
) = runInventoryFilterScriptInternal(fileName, inventories, diagnostics::accept)

fun runJavaBasedScript(fileName: String) {
    val receiver = AnotherReceiver()
    val result = evalFile(File(fileName).toScriptSource(), receiver)
    result.reports.forEach {
        if (it.severity > ScriptDiagnostic.Severity.DEBUG) {
            println(" : ${it.message}" + if (it.exception == null) "" else ": ${it.exception}")
        }
    }
}

private fun runInventoryFilterScriptInternal(
    fileName: String,
    inventories: Map,
    block: (ScriptDiagnostic) -> Unit
) {
    val receiver = InventoryFilterImplicitReceiver(InventoryReader(), InventoryWriter(), inventories, Predicates())
    val result = evalFile(File(fileName).toScriptSource(), receiver)
    result.reports.forEach {
        if (it.severity > ScriptDiagnostic.Severity.DEBUG) {
            block.invoke(it)
        }
    }
}

private inline fun  evalFile(
    sourceCode: SourceCode,
    receiver: Any
): ResultWithDiagnostics {
    val compilationConfiguration = createJvmCompilationConfigurationFromTemplate()
    val evaluationConfiguration = createJvmEvaluationConfigurationFromTemplate {
        implicitReceivers(receiver)
    }
    return BasicJvmScriptingHost().eval(sourceCode, compilationConfiguration, evaluationConfiguration)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy