2 * Copyright © 2017-2018 AT&T Intellectual Property.
3 * Modifications Copyright © 2018 IBM.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 package org.onap.ccsdk.cds.controllerblueprints.core.scripts
20 import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
21 import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoots
22 import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback
23 import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
24 import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
25 import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
26 import org.jetbrains.kotlin.cli.common.messages.MessageCollector
27 import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
28 import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
29 import org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler
30 import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot
31 import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer
32 import org.jetbrains.kotlin.config.*
33 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
34 import org.slf4j.LoggerFactory
35 import kotlin.script.experimental.api.*
36 import kotlin.script.experimental.host.ScriptingHostConfiguration
37 import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty
38 import kotlin.script.experimental.jvmhost.KJvmCompilerProxy
40 open class BluePrintsCompilerProxy(private val hostConfiguration: ScriptingHostConfiguration) : KJvmCompilerProxy {
42 private val log = LoggerFactory.getLogger(BluePrintsCompilerProxy::class.java)!!
44 override fun compile(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration)
45 : ResultWithDiagnostics<CompiledScript<*>> {
47 val messageCollector = ScriptDiagnosticsMessageCollector()
49 fun failure(vararg diagnostics: ScriptDiagnostic): ResultWithDiagnostics.Failure =
50 ResultWithDiagnostics.Failure(*messageCollector.diagnostics.toTypedArray(), *diagnostics)
55 log.trace("Scripting Host Configuration : $hostConfiguration")
57 setIdeaIoUseFallback()
59 val blueprintSourceCode = script as BluePrintSourceCode
61 val compiledJarFile = blueprintSourceCode.targetJarFile
63 /** Check cache is present for the blueprint scripts */
64 val hasCompiledCache = BluePrintCompileCache.hasClassLoader(blueprintSourceCode.cacheKey)
66 if (!compiledJarFile.exists() || blueprintSourceCode.regenerate || !hasCompiledCache) {
67 log.info("compiling for cache key(${blueprintSourceCode.cacheKey})")
69 var environment: KotlinCoreEnvironment? = null
71 val rootDisposable = Disposer.newDisposable()
75 // Clean the cache, if present
76 if (hasCompiledCache) {
77 BluePrintCompileCache.cleanClassLoader(blueprintSourceCode.cacheKey)
80 val compilerConfiguration = CompilerConfiguration().apply {
82 put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector)
83 put(CommonConfigurationKeys.MODULE_NAME, blueprintSourceCode.moduleName)
84 put(JVMConfigurationKeys.OUTPUT_JAR, compiledJarFile)
85 put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, false)
87 // Load Current Class loader to Compilation Class loader
88 val currentClassLoader = classpathFromClasspathProperty()
89 currentClassLoader?.forEach {
90 add(CLIConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(it))
93 // Add all Kotlin Sources
94 addKotlinSourceRoots(blueprintSourceCode.blueprintKotlinSources)
95 // for Kotlin 1.3.30 greater
96 //add(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, ScriptingCompilerConfigurationComponentRegistrar())
98 languageVersionSettings = LanguageVersionSettingsImpl(
99 LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE, mapOf(AnalysisFlags.skipMetadataVersionCheck to true)
103 //log.info("Executing with compiler configuration : $compilerConfiguration")
105 environment = KotlinCoreEnvironment.createForProduction(rootDisposable, compilerConfiguration,
106 EnvironmentConfigFiles.JVM_CONFIG_FILES)
108 // Compile Kotlin Sources
109 val compiled = KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment)
111 val analyzerWithCompilerReport = AnalyzerWithCompilerReport(messageCollector,
112 environment.configuration.languageVersionSettings)
114 if (analyzerWithCompilerReport.hasErrors()) {
115 return ResultWithDiagnostics.Failure(messageCollector.diagnostics)
118 rootDisposable.dispose()
122 checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" }
124 val compiledScript = BluePrintCompiledScript<String>(blueprintSourceCode.cacheKey, scriptCompilationConfiguration)
126 return compiledScript.asSuccess()
128 } catch (ex: Throwable) {
129 return failure(ex.asDiagnostics())
134 class ScriptDiagnosticsMessageCollector : MessageCollector {
136 private val _diagnostics = arrayListOf<ScriptDiagnostic>()
138 val diagnostics: List<ScriptDiagnostic> get() = _diagnostics
140 override fun clear() {
144 override fun hasErrors(): Boolean =
145 _diagnostics.any { it.severity == ScriptDiagnostic.Severity.ERROR }
148 override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
149 val mappedSeverity = when (severity) {
150 CompilerMessageSeverity.EXCEPTION,
151 CompilerMessageSeverity.ERROR -> ScriptDiagnostic.Severity.ERROR
152 CompilerMessageSeverity.STRONG_WARNING,
153 CompilerMessageSeverity.WARNING -> ScriptDiagnostic.Severity.WARNING
154 CompilerMessageSeverity.INFO -> ScriptDiagnostic.Severity.INFO
155 CompilerMessageSeverity.LOGGING -> ScriptDiagnostic.Severity.DEBUG
158 if (mappedSeverity != null) {
159 val mappedLocation = location?.let {
160 if (it.line < 0 && it.column < 0) null // special location created by CompilerMessageLocation.create
161 else SourceCode.Location(SourceCode.Position(it.line, it.column))
163 _diagnostics.add(ScriptDiagnostic(message, mappedSeverity, location?.path, mappedLocation))