Scripting: remove obsolete script-util module

#KT-58367 fixed
This commit is contained in:
Ilya Chernikov
2023-11-15 14:54:31 +01:00
committed by Space Team
parent c332e1beb5
commit 6877fa8e42
18 changed files with 0 additions and 949 deletions
-1
View File
@@ -329,7 +329,6 @@
/libraries/tools/kotlin-noarg/ "Kotlin Build Tools"
/libraries/tools/kotlin-prepush-hook/ "Kotlin Build Infrastructure"
/libraries/tools/kotlin-sam-with-receiver/ "Kotlin Build Tools"
/libraries/tools/kotlin-script-util/ "Kotlin Compiler Core"
/libraries/tools/kotlin-serialization/ "Kotlin Build Tools"
/libraries/tools/kotlin-serialization-unshaded/ "Kotlin Build Tools"
/libraries/tools/kotlin-stdlib-docs/ A.Qurbonzoda Vsevolod.Tolstopyato Ilya.Gorbunov Filipp.Zhinkin
@@ -1,40 +0,0 @@
description = "Kotlin scripting support utilities"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
api(kotlinStdlib())
api(project(":kotlin-script-runtime"))
api(project(":kotlin-scripting-jvm"))
api(commonDependency("org.jetbrains.intellij.deps", "trove4j"))
compileOnly(project(":compiler:cli"))
compileOnly(project(":daemon-common"))
compileOnly(project(":kotlin-scripting-compiler"))
api(project(":kotlin-daemon-client"))
testCompileOnly(project(":compiler:cli"))
testApi(project(":kotlin-test:kotlin-test-junit"))
testImplementation(libs.junit4)
testApi(project(":kotlin-scripting-compiler"))
testRuntimeOnly(project(":kotlin-compiler"))
testApi(intellijCore())
}
optInToExperimentalCompilerApi()
configurations.all {
resolutionStrategy {
force(libs.junit4)
}
}
projectTest {
workingDir = rootDir
}
runtimeJar()
sourcesJar()
javadocJar()
@@ -1,85 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.script.jsr223
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.common.repl.*
import org.jetbrains.kotlin.daemon.client.DaemonReportMessage
import org.jetbrains.kotlin.daemon.client.DaemonReportingTargets
import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient
import org.jetbrains.kotlin.daemon.client.KotlinRemoteReplCompilerClient
import org.jetbrains.kotlin.daemon.common.*
import java.io.File
import java.io.OutputStream
import java.io.PrintStream
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.script.ScriptContext
import javax.script.ScriptEngineFactory
import javax.script.ScriptException
import kotlin.reflect.KClass
// TODO: need to manage resources here, i.e. call replCompiler.dispose when engine is collected
@Deprecated("Use kotlin-scripting-jsr223 instead")
class KotlinJsr223JvmDaemonCompileScriptEngine(
factory: ScriptEngineFactory,
compilerClasspath: List<File>,
templateClasspath: List<File>,
templateClassName: String,
val getScriptArgs: (ScriptContext, Array<out KClass<out Any>>?) -> ScriptArgsWithTypes?,
val scriptArgsTypes: Array<out KClass<out Any>>?,
compilerOut: OutputStream = System.err
) : KotlinJsr223JvmScriptEngineBase(factory), KotlinJsr223JvmInvocableScriptEngine {
private val daemon by lazy { connectToCompileService(compilerClasspath) }
override val replCompiler by lazy {
daemon.let {
KotlinRemoteReplCompilerClient(
it,
makeAutodeletingFlagFile("jsr223-repl-session"),
CompileService.TargetPlatform.JVM,
emptyArray(),
PrintingMessageCollector(PrintStream(compilerOut), MessageRenderer.WITHOUT_PATHS, false),
templateClasspath,
templateClassName)
}
}
// TODO: bindings passing works only once on the first eval, subsequent setContext/setBindings call have no effect. Consider making it dynamic, but take history into account
val localEvaluator by lazy { GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader, getScriptArgs(getContext(), scriptArgsTypes)) }
override val replEvaluator: ReplFullEvaluator get() = localEvaluator
override val state: IReplStageState<*> get() = getCurrentState(getContext())
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock)
override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = getScriptArgs(context, scriptArgsTypes)
private fun connectToCompileService(compilerCP: List<File>): CompileService {
val compilerId = CompilerId.makeCompilerId(*compilerCP.toTypedArray())
val daemonOptions = configureDaemonOptions()
val daemonJVMOptions = DaemonJVMOptions()
val daemonReportMessages = arrayListOf<DaemonReportMessage>()
return KotlinCompilerClient.connectToCompileService(compilerId, daemonJVMOptions, daemonOptions, DaemonReportingTargets(null, daemonReportMessages), true, true)
?: throw ScriptException("Unable to connect to repl server:" + daemonReportMessages.joinToString("\n ", prefix = "\n ") { "${it.category.name} ${it.message}" })
}
}
@@ -1,83 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.script.jsr223
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.common.repl.*
import org.jetbrains.kotlin.cli.jvm.config.configureJdkClasspathRoots
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.cli.jvm.config.addJvmSdkRoots
import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar
import org.jetbrains.kotlin.scripting.compiler.plugin.repl.GenericReplCompiler
import org.jetbrains.kotlin.scripting.definitions.KotlinScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.net.URLClassLoader
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.script.ScriptContext
import javax.script.ScriptEngineFactory
import kotlin.reflect.KClass
@Deprecated("Use kotlin-scripting-jsr223 instead")
class KotlinJsr223JvmLocalScriptEngine(
factory: ScriptEngineFactory,
val templateClasspath: List<File>,
templateClassName: String,
val getScriptArgs: (ScriptContext, Array<out KClass<out Any>>?) -> ScriptArgsWithTypes?,
val scriptArgsTypes: Array<out KClass<out Any>>?
) : KotlinJsr223JvmScriptEngineBase(factory), KotlinJsr223JvmInvocableScriptEngine {
override val replCompiler: ReplCompiler by lazy {
GenericReplCompiler(
makeScriptDefinition(templateClasspath, templateClassName),
makeCompilerConfiguration(),
PrintingMessageCollector(System.out, MessageRenderer.WITHOUT_PATHS, false))
}
// TODO: bindings passing works only once on the first eval, subsequent setContext/setBindings call have no effect. Consider making it dynamic, but take history into account
private val localEvaluator by lazy { GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader, getScriptArgs(getContext(), scriptArgsTypes)) }
override val replEvaluator: ReplFullEvaluator get() = localEvaluator
override val state: IReplStageState<*> get() = getCurrentState(getContext())
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock)
override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = getScriptArgs(context, scriptArgsTypes)
private fun makeScriptDefinition(templateClasspath: List<File>, templateClassName: String): KotlinScriptDefinition {
val classloader = URLClassLoader(templateClasspath.map { it.toURI().toURL() }.toTypedArray(), this.javaClass.classLoader)
val cls = classloader.loadClass(templateClassName)
return KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, emptyMap())
}
private fun makeCompilerConfiguration() = CompilerConfiguration().apply {
addJvmSdkRoots(PathUtil.getJdkClassesRootsFromCurrentJre())
addJvmClasspathRoots(templateClasspath)
configureJdkClasspathRoots()
add(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, ScriptingCompilerConfigurationComponentRegistrar())
put(CommonConfigurationKeys.MODULE_NAME, "kotlin-script")
languageVersionSettings = LanguageVersionSettingsImpl(
LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE, mapOf(AnalysisFlags.skipMetadataVersionCheck to true)
)
}
}
@@ -1,55 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "DEPRECATION") // could be used externally in javax.script.ScriptEngineFactory META-INF file
package org.jetbrains.kotlin.script.jsr223
import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBase
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
import javax.script.Bindings
import javax.script.ScriptContext
import javax.script.ScriptEngine
import kotlin.script.experimental.jvm.util.KotlinJars
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
@Deprecated("Use kotlin-scripting-jsr223 instead")
class KotlinJsr223JvmLocalScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {
override fun getScriptEngine(): ScriptEngine =
KotlinJsr223JvmLocalScriptEngine(
this,
scriptCompilationClasspathFromContext("kotlin-script-util.jar", wholeClasspath = true),
KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
{ ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
arrayOf(Bindings::class)
)
}
@Deprecated("Use kotlin-scripting-jsr223 instead")
class KotlinJsr223JvmDaemonLocalEvalScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {
override fun getScriptEngine(): ScriptEngine =
KotlinJsr223JvmDaemonCompileScriptEngine(
this,
KotlinJars.compilerWithScriptingClasspath,
scriptCompilationClasspathFromContext("kotlin-script-util.jar", wholeClasspath = true),
KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
{ ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
arrayOf(Bindings::class)
)
}
@@ -1,43 +0,0 @@
package org.jetbrains.kotlin.script.jsr223
import org.jetbrains.kotlin.cli.common.repl.KOTLIN_SCRIPT_ENGINE_BINDINGS_KEY
import org.jetbrains.kotlin.cli.common.repl.KOTLIN_SCRIPT_STATE_BINDINGS_KEY
import javax.script.Bindings
import javax.script.ScriptEngine
import kotlin.script.templates.ScriptTemplateDefinition
import kotlin.script.templates.standard.ScriptTemplateWithBindings
@Suppress("unused")
@ScriptTemplateDefinition
@Deprecated("Use kotlin-scripting-jsr223 instead")
abstract class KotlinStandardJsr223ScriptTemplate(val jsr223Bindings: Bindings) : ScriptTemplateWithBindings(jsr223Bindings) {
private val myEngine: ScriptEngine? get() = bindings[KOTLIN_SCRIPT_ENGINE_BINDINGS_KEY]?.let { it as? ScriptEngine }
private inline fun<T> withMyEngine(body: (ScriptEngine) -> T): T =
myEngine?.let(body) ?: throw IllegalStateException("Script engine for `eval` call is not found")
fun eval(script: String, newBindings: Bindings): Any? =
withMyEngine {
val savedState = newBindings[KOTLIN_SCRIPT_STATE_BINDINGS_KEY]?.takeIf { it === this.jsr223Bindings[KOTLIN_SCRIPT_STATE_BINDINGS_KEY] }?.apply {
newBindings[KOTLIN_SCRIPT_STATE_BINDINGS_KEY] = null
}
val res = it.eval(script, newBindings)
savedState?.apply {
newBindings[KOTLIN_SCRIPT_STATE_BINDINGS_KEY] = savedState
}
res
}
fun eval(script: String): Any? =
withMyEngine {
val savedState = jsr223Bindings.remove(KOTLIN_SCRIPT_STATE_BINDINGS_KEY)
val res = it.eval(script, jsr223Bindings)
savedState?.apply {
jsr223Bindings[KOTLIN_SCRIPT_STATE_BINDINGS_KEY] = savedState
}
res
}
fun createBindings(): Bindings = withMyEngine { it.createBindings() }
}
@@ -1,41 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.script.util
@Deprecated("Use annotations an processing code from the kotlin-scripting-dependencies library")
@Target(AnnotationTarget.FILE)
@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class DependsOn(val value: String = "", val groupId: String = "", val artifactId: String = "", val version: String = "")
@Deprecated("Use annotations an processing code from the kotlin-scripting-dependencies library")
@Target(AnnotationTarget.FILE)
@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class Repository(val value: String = "", val id: String = "", val url: String = "")
@Deprecated("Use your own annotations, this will be removed soon")
@Target(AnnotationTarget.FILE)
@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class Import(vararg val paths: String)
@Deprecated("Use your own annotations, this will be removed soon")
@Target(AnnotationTarget.FILE)
@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class CompilerOptions(vararg val options: String)
@@ -1,61 +0,0 @@
package org.jetbrains.kotlin.script.util
import java.io.File
import kotlin.reflect.KClass
import kotlin.script.experimental.jvm.util.matchMaybeVersionedFile as newMatchMaybeVersionedFile
import kotlin.script.experimental.jvm.util.hasParentNamed as newHasParentName
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun classpathFromClassloader(classLoader: ClassLoader): List<File>? =
kotlin.script.experimental.jvm.util.classpathFromClassloader(classLoader)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun classpathFromClasspathProperty(): List<File>? =
kotlin.script.experimental.jvm.util.classpathFromClasspathProperty()
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun classpathFromClass(classLoader: ClassLoader, klass: KClass<out Any>): List<File>? =
kotlin.script.experimental.jvm.util.classpathFromClass(classLoader, klass)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun classpathFromFQN(classLoader: ClassLoader, fqn: String): List<File>? =
kotlin.script.experimental.jvm.util.classpathFromFQN(classLoader, fqn)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun File.matchMaybeVersionedFile(baseName: String) = newMatchMaybeVersionedFile(baseName)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun File.hasParentNamed(baseName: String): Boolean = newHasParentName(baseName)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun scriptCompilationClasspathFromContextOrNull(
vararg keyNames: String,
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
wholeClasspath: Boolean = false
): List<File>? =
kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContextOrNull(
*keyNames, classLoader = classLoader, wholeClasspath = wholeClasspath
)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun scriptCompilationClasspathFromContextOrStlib(
vararg keyNames: String,
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
wholeClasspath: Boolean = false
): List<File> =
kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContextOrStdlib(
*keyNames, classLoader = classLoader, wholeClasspath = wholeClasspath
)
@Deprecated("Use the function from kotlin.script.experimental.jvm.util")
fun scriptCompilationClasspathFromContext(
vararg keyNames: String,
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
wholeClasspath: Boolean = false
): List<File> =
kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext(
*keyNames, classLoader = classLoader, wholeClasspath = wholeClasspath
)
@Deprecated("Use the object from kotlin.script.experimental.jvm.util")
val KotlinJars = kotlin.script.experimental.jvm.util.KotlinJars
@@ -1,82 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.script.util
import org.jetbrains.kotlin.script.util.resolvers.DirectResolver
import org.jetbrains.kotlin.script.util.resolvers.FlatLibDirectoryResolver
import org.jetbrains.kotlin.script.util.resolvers.Resolver
import org.jetbrains.kotlin.scripting.resolve.InvalidScriptResolverAnnotation
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.io.File
import java.util.concurrent.Future
import kotlin.script.dependencies.KotlinScriptExternalDependencies
import kotlin.script.dependencies.ScriptContents
import kotlin.script.dependencies.ScriptDependenciesResolver
import kotlin.script.dependencies.asFuture
import kotlin.script.templates.AcceptedAnnotations
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies and kotlin-scripting-dependencies-maven")
open class KotlinAnnotatedScriptDependenciesResolver(val baseClassPath: List<File>, resolvers: Iterable<Resolver>)
: ScriptDependenciesResolver
{
private val resolvers: MutableList<Resolver> = resolvers.toMutableList()
inner class ResolvedDependencies(previousDependencies: KotlinScriptExternalDependencies?, depsFromAnnotations: List<File> ) : KotlinScriptExternalDependencies {
override val classpath = if (resolvers.isEmpty()) baseClassPath else baseClassPath + depsFromAnnotations
override val imports = if (previousDependencies != null) emptyList() else listOf(DependsOn::class.java.`package`.name + ".*")
}
@AcceptedAnnotations(DependsOn::class, Repository::class)
override fun resolve(script: ScriptContents,
environment: Map<String, Any?>?,
report: (ScriptDependenciesResolver.ReportSeverity, String, ScriptContents.Position?) -> Unit,
previousDependencies: KotlinScriptExternalDependencies?
): Future<KotlinScriptExternalDependencies?> {
val depsFromAnnotations: List<File> = resolveFromAnnotations(script)
return (if (previousDependencies != null && depsFromAnnotations.isEmpty()) previousDependencies
else ResolvedDependencies(previousDependencies, depsFromAnnotations)
).asFuture()
}
private fun resolveFromAnnotations(script: ScriptContents): List<File> {
script.annotations.forEach { annotation ->
when (annotation) {
is Repository -> {
val isFlat: Boolean = resolvers.firstIsInstanceOrNull<FlatLibDirectoryResolver>()?.tryAddRepo(annotation)
?: (FlatLibDirectoryResolver.tryCreate(annotation)?.also { resolvers.add(it) } != null)
if (!isFlat) {
resolvers.find { it !is FlatLibDirectoryResolver && it.tryAddRepo(annotation) }
?: throw IllegalArgumentException("Illegal argument for Repository annotation: $annotation")
}
}
is DependsOn -> {}
is InvalidScriptResolverAnnotation -> throw Exception("Invalid annotation ${annotation.name}", annotation.error)
else -> throw Exception("Unknown annotation ${annotation.javaClass}")
}
}
return script.annotations.filterIsInstance(DependsOn::class.java).flatMap { dep ->
resolvers.asSequence().mapNotNull { it.tryResolve(dep) }.firstOrNull() ?:
throw Exception("Unable to resolve dependency $dep")
}
}
}
@Deprecated("Use FileSystemDependenciesResolver from kotlin-scripting-dependencies instead")
class LocalFilesResolver :
KotlinAnnotatedScriptDependenciesResolver(emptyList(), arrayListOf(DirectResolver()))
@@ -1,85 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.script.util.resolvers
import org.jetbrains.kotlin.script.util.Repository
import org.jetbrains.kotlin.script.util.resolvers.experimental.*
import java.io.File
import java.net.MalformedURLException
import java.net.URL
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
class DirectResolver : GenericRepositoryWithBridge {
override fun tryResolve(artifactCoordinates: GenericArtifactCoordinates): Iterable<File>? =
artifactCoordinates.string.takeUnless(String::isBlank)
?.let(::File)?.takeIf { it.exists() && (it.isFile || it.isDirectory) }?.let { listOf(it) }
override fun tryAddRepository(repositoryCoordinates: GenericRepositoryCoordinates): Boolean = false
}
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
class FlatLibDirectoryResolver(vararg paths: File) : GenericRepositoryWithBridge {
private val localRepos = arrayListOf<File>()
init {
for (path in paths) {
if (!path.exists() || !path.isDirectory) throw IllegalArgumentException("Invalid flat lib directory repository path '$path'")
}
localRepos.addAll(paths)
}
override fun tryResolve(artifactCoordinates: GenericArtifactCoordinates): Iterable<File>? {
for (path in localRepos) {
// TODO: add coordinates and wildcard matching
val res = artifactCoordinates.string.takeUnless(String::isBlank)
?.let { File(path, it) }
?.takeIf { it.exists() && (it.isFile || it.isDirectory) }
if (res != null) return listOf(res)
}
return null
}
override fun tryAddRepository(repositoryCoordinates: GenericRepositoryCoordinates): Boolean {
val repoDir = repositoryCoordinates.file ?: return false
localRepos.add(repoDir)
return true
}
companion object {
fun tryCreate(annotation: Repository): FlatLibDirectoryResolver? = tryCreate(
BasicRepositoryCoordinates(
annotation.url.takeUnless(String::isBlank) ?: annotation.value, annotation.id.takeUnless(String::isBlank)
)
)
fun tryCreate(repositoryCoordinates: GenericRepositoryCoordinates): FlatLibDirectoryResolver? =
repositoryCoordinates.file?.let { FlatLibDirectoryResolver(it) }
}
}
internal fun String.toRepositoryUrlOrNull(): URL? =
try {
URL(this)
} catch (_: MalformedURLException) {
null
}
internal fun String.toRepositoryFileOrNull(): File? =
File(this).takeIf { it.exists() && it.isDirectory }
@@ -1,76 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.script.util.resolvers.experimental
import org.jetbrains.kotlin.script.util.DependsOn
import org.jetbrains.kotlin.script.util.Repository
import org.jetbrains.kotlin.script.util.resolvers.Resolver
import org.jetbrains.kotlin.script.util.resolvers.toRepositoryFileOrNull
import org.jetbrains.kotlin.script.util.resolvers.toRepositoryUrlOrNull
import java.io.File
import java.net.URL
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
interface GenericArtifactCoordinates {
val string: String
}
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
interface GenericRepositoryCoordinates {
val string: String
val name: String? get() = null
val url: URL? get() = string.toRepositoryUrlOrNull()
val file: File? get() = (url?.takeIf { it.protocol == "file" }?.path ?: string).toRepositoryFileOrNull()
}
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
interface GenericResolver {
fun tryResolve(artifactCoordinates: GenericArtifactCoordinates): Iterable<File>?
fun tryAddRepository(repositoryCoordinates: GenericRepositoryCoordinates): Boolean
fun tryResolve(artifactCoordinates: String): Iterable<File>? = tryResolve(BasicArtifactCoordinates(artifactCoordinates))
fun tryAddRepository(repositoryCoordinates: String, id: String? = null): Boolean =
tryAddRepository(BasicRepositoryCoordinates(repositoryCoordinates, id))
}
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
open class BasicArtifactCoordinates(override val string: String) : GenericArtifactCoordinates
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
open class BasicRepositoryCoordinates(override val string: String, override val name: String? = null) : GenericRepositoryCoordinates
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
interface GenericRepositoryWithBridge : GenericResolver, Resolver {
override fun tryResolve(dependsOn: DependsOn): Iterable<File>? =
tryResolve(
with(dependsOn) {
MavenArtifactCoordinates(value, groupId, artifactId, version)
}
)
override fun tryAddRepo(annotation: Repository): Boolean =
with(annotation) {
tryAddRepository(
value.takeIf { it.isNotBlank() } ?: url,
id.takeIf { it.isNotBlank() }
)
}
}
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
open class MavenArtifactCoordinates(
val value: String?,
val groupId: String?,
val artifactId: String?,
val version: String?
) : GenericArtifactCoordinates {
override val string: String
get() = value.takeIf { it?.isNotBlank() ?: false }
?: listOf(groupId, artifactId, version).filter { it?.isNotBlank() ?: false }.joinToString(":")
}
@@ -1,18 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.script.util.resolvers
import org.jetbrains.kotlin.script.util.DependsOn
import org.jetbrains.kotlin.script.util.Repository
import java.io.File
@Deprecated("Use new resolving classes from kotlin-scripting-dependencies")
interface Resolver {
fun tryResolve(dependsOn: DependsOn): Iterable<File>?
fun tryAddRepo(annotation: Repository): Boolean
}
@@ -1,28 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "DEPRECATION")
package org.jetbrains.kotlin.script.util.templates
import org.jetbrains.kotlin.script.util.LocalFilesResolver
import kotlin.script.templates.ScriptTemplateDefinition
@ScriptTemplateDefinition(resolver = LocalFilesResolver::class, scriptFilePattern = ".*\\.kts")
abstract class StandardArgsScriptTemplateWithLocalResolving(val args: Array<String>)
@ScriptTemplateDefinition(resolver = LocalFilesResolver::class, scriptFilePattern = ".*\\.kts")
abstract class BindingsScriptTemplateWithLocalResolving(val bindings: Map<String, Any?>)
@@ -1,221 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.script.util
import com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoot
import org.jetbrains.kotlin.cli.common.messages.*
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.config.configureJdkClasspathRoots
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoot
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.cli.jvm.config.jvmClasspathRoots
import org.jetbrains.kotlin.codegen.CompilationException
import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.script.util.templates.BindingsScriptTemplateWithLocalResolving
import org.jetbrains.kotlin.script.util.templates.StandardArgsScriptTemplateWithLocalResolving
import org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar
import org.jetbrains.kotlin.scripting.compiler.plugin.impl.ScriptJvmCompilerFromEnvironment
import org.jetbrains.kotlin.scripting.compiler.plugin.toCompilerMessageSeverity
import org.jetbrains.kotlin.scripting.configuration.ScriptingConfigurationKeys
import org.jetbrains.kotlin.scripting.definitions.KotlinScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinitionProvider
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.utils.PathUtil.getResourcePathForClass
import org.junit.Assert
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import kotlin.reflect.KClass
import kotlin.script.experimental.api.onSuccess
import kotlin.script.experimental.api.valueOr
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.impl.internalScriptingRunSuspend
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
const val KOTLIN_JAVA_RUNTIME_JAR = "kotlin-stdlib.jar"
class ScriptUtilIT {
companion object {
private const val argsHelloWorldOutput =
"""Hello, world!
a1
done
"""
private const val bindingsHelloWorldOutput =
"""Hello, world!
a1 = 42
done
"""
}
@Test
fun testArgsHelloWorld() {
val scriptClass = compileScript("args-hello-world.kts", StandardArgsScriptTemplateWithLocalResolving::class)
Assert.assertNotNull(scriptClass)
val ctor = scriptClass?.getConstructor(Array<String>::class.java)
Assert.assertNotNull(ctor)
captureOut {
ctor!!.newInstance(arrayOf("a1"))
}.let {
Assert.assertEquals(argsHelloWorldOutput.linesSplitTrim(), it.linesSplitTrim())
}
}
@Test
fun testBndHelloWorld() {
val scriptClass = compileScript("bindings-hello-world.kts", BindingsScriptTemplateWithLocalResolving::class)
Assert.assertNotNull(scriptClass)
val ctor = scriptClass?.getConstructor(Map::class.java)
Assert.assertNotNull(ctor)
captureOut {
ctor!!.newInstance(hashMapOf("a1" to 42))
}.let {
Assert.assertEquals(bindingsHelloWorldOutput.linesSplitTrim(), it.linesSplitTrim())
}
}
private fun compileScript(
scriptFileName: String,
scriptTemplate: KClass<out Any>,
environment: Map<String, Any?>? = null,
suppressOutput: Boolean = false
): Class<*>? =
compileScriptImpl(
"libraries/tools/kotlin-script-util/src/test/resources/scripts/$scriptFileName",
KotlinScriptDefinitionFromAnnotatedTemplate(
scriptTemplate,
environment
), suppressOutput
)
private fun compileScriptImpl(
scriptPath: String,
scriptDefinition: KotlinScriptDefinition,
suppressOutput: Boolean
): Class<*>? {
val messageCollector =
if (suppressOutput) MessageCollector.NONE
else PrintingMessageCollector(System.err, MessageRenderer.PLAIN_FULL_PATHS, true)
val rootDisposable = Disposer.newDisposable()
try {
val configuration = CompilerConfiguration().apply {
addJvmClasspathRoots(scriptCompilationClasspathFromContext(KOTLIN_JAVA_RUNTIME_JAR))
configureJdkClasspathRoots()
put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector)
addKotlinSourceRoot(scriptPath)
@Suppress("DEPRECATION")
getResourcePathForClass(DependsOn::class.java).let {
if (it.exists()) {
addJvmClasspathRoot(it)
}
}
put(CommonConfigurationKeys.MODULE_NAME, "kotlin-script-util-test")
add(
ScriptingConfigurationKeys.SCRIPT_DEFINITIONS,
ScriptDefinition.FromLegacy(
defaultJvmScriptingHostConfiguration, scriptDefinition
)
)
put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, true)
add(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, ScriptingCompilerConfigurationComponentRegistrar())
}
val environment = KotlinCoreEnvironment.createForTests(rootDisposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES)
environment.getSourceFiles().forEach {
messageCollector.report(CompilerMessageSeverity.LOGGING, "file: $it -> script def: ${it.findScriptDefinition()?.name}")
}
messageCollector.report(
CompilerMessageSeverity.LOGGING,
"compilation classpath:\n ${environment.configuration.jvmClasspathRoots.joinToString("\n ")}"
)
val scriptCompiler = ScriptJvmCompilerFromEnvironment(environment)
return try {
val script = File(scriptPath).toScriptSource()
val newScriptDefinition = ScriptDefinitionProvider.getInstance(environment.project)!!.findDefinition(script)!!
val compiledScript = scriptCompiler.compile(script, newScriptDefinition.compilationConfiguration).onSuccess {
@Suppress("DEPRECATION_ERROR")
internalScriptingRunSuspend {
it.getClass(newScriptDefinition.evaluationConfiguration)
}
}.valueOr {
for (report in it.reports) {
messageCollector.report(report.severity.toCompilerMessageSeverity(), report.render(withSeverity = false))
}
return null
}
compiledScript.java
} catch (e: CompilationException) {
messageCollector.report(
CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(e),
MessageUtil.psiElementToMessageLocation(e.element)
)
null
} catch (e: IllegalStateException) {
messageCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(e))
null
} catch (t: Throwable) {
MessageCollectorUtil.reportException(messageCollector, t)
throw t
}
} finally {
Disposer.dispose(rootDisposable)
}
}
private fun String.linesSplitTrim() =
split('\n', '\r').map(String::trim).filter(String::isNotBlank)
private fun captureOut(body: () -> Unit): String = captureOutAndErr(body).first
private fun captureOutAndErr(body: () -> Unit): Pair<String, String> {
val outStream = ByteArrayOutputStream()
val errStream = ByteArrayOutputStream()
val prevOut = System.out
val prevErr = System.err
System.setOut(PrintStream(outStream))
System.setErr(PrintStream(errStream))
try {
body()
} finally {
System.out.flush()
System.err.flush()
System.setOut(prevOut)
System.setErr(prevErr)
}
return outStream.toString() to errStream.toString()
}
}
@@ -1,8 +0,0 @@
println("Hello, world!")
if (args.isNotEmpty()) {
println(args.joinToString())
}
println("done")
@@ -1,12 +0,0 @@
@file:DependsOn("junit:junit:4.11")
org.junit.Assert.assertTrue(true)
println("Hello, world!")
if (args.isNotEmpty()) {
println(args.joinToString())
}
println("done")
@@ -1,8 +0,0 @@
println("Hello, world!")
if (bindings.isNotEmpty()) {
println(bindings.entries.joinToString { "${it.key} = ${it.value}" })
}
println("done")
-2
View File
@@ -226,7 +226,6 @@ include ":kotlin-imports-dumper-compiler-plugin",
":kotlin-assignment",
":kotlin-gradle-subplugin-example",
":examples:annotation-processor-example",
":kotlin-script-util",
":kotlin-annotation-processing",
":kotlin-annotation-processing-cli",
":kotlin-annotation-processing-base",
@@ -762,7 +761,6 @@ project(':kotlin-assignment').projectDir = "$rootDir/libraries/tools/kotlin-assi
project(':kotlin-lombok').projectDir = "$rootDir/libraries/tools/kotlin-lombok" as File
project(':kotlin-gradle-subplugin-example').projectDir = "$rootDir/libraries/examples/kotlin-gradle-subplugin-example" as File
project(':examples:annotation-processor-example').projectDir = "$rootDir/libraries/examples/annotation-processor-example" as File
project(':kotlin-script-util').projectDir = "$rootDir/libraries/tools/kotlin-script-util" as File
project(':kotlin-annotation-processing-embeddable').projectDir = "$rootDir/plugins/kapt3/kotlin-annotation-processing-embeddable" as File
project(':kotlin-daemon-embeddable').projectDir = "$rootDir/prepare/kotlin-daemon-embeddable" as File
project(':kotlin-annotation-processing-compiler').projectDir = "$rootDir/plugins/kapt3/kapt3-compiler" as File