GithubHelp home page GithubHelp logo

kotlin / kotlin-script-examples Goto Github PK

View Code? Open in Web Editor NEW
291.0 32.0 41.0 210 KB

Examples of Kotlin Scripts and usages of the Kotlin Scripting API

License: Apache License 2.0

Kotlin 100.00%
kotlin kotlin-script

kotlin-script-examples's Introduction

JetBrains incubator project

Kotlin scripting examples

This repository contains example projects and individual scripts, as well as links to the external examples demonstrating Kotlin Scripting functionality and API usage.

If you know good examples of the Kotlin scripting API usage, not mentioned here, please submit an issue or a pull request with the link and short description.

Examples in this repository

The complete project could be compiled with Gradle, as well as imported e.g. in IntelliJ IDEA.

The individual example projects are mostly independent and could be copied and reused independently, but build files should be adapted accordingly, mostly to supply required Kotlin version properties and setup inter-project dependencies when needed

Script definitions with scripting hosts

External examples

License

The Apache 2 license (given in full in LICENSE.txt applies to all code in this repository which is copyright by JetBrains.

kotlin-script-examples's People

Contributors

a2xchip avatar alexbeggs avatar astronaut4449 avatar khouari1 avatar ligee avatar lorenzsimon avatar ludeknovy avatar martinbonnin avatar nisrulz avatar strangemonad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlin-script-examples's Issues

Can't bind to engine

import org.junit.Test
import javax.script.ScriptEngineManager
import kotlin.test.assertEquals

class ScriptTest {

@Test
fun testSimpleEval() {
    val engine = ScriptEngineManager().getEngineByExtension("kts")!!
    val res = engine.eval("2+4")
    assertEquals(6,res)
}

@Test
fun testSimpleBinding() {
    val engine = ScriptEngineManager().getEngineByExtension("kts")!!
    engine.put("hello","world")
    val res = engine.eval("hello")
    assertEquals("world",res)
}

}

I've got

javax.script.ScriptException: Unresolved reference: hello
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compileAndEval(KotlinJsr223JvmScriptEngineBase.kt:65)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.eval(KotlinJsr223JvmScriptEngineBase.kt:31)

No documentation provided for Repository interface

Hello,

I was not able to find any documentation wrt the Repository interface.

My current problem is that I can't find a way to provide credentials to a private Nexus registry

I have created a topic in Kotlin lang Discourse

Once I discover how to provide credentials to @RepositoryI'll be able to submit a PR with an example.

If anybody can help with that, please let me know!

KotlinJsr223DefaultScriptEngineFactory not needed anymore?

Sorry for this question-like type of issue, but when reading though

I was wondering why there is no META-INF/services/javax.script.ScriptEngineFactory file anymore which contains the string kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory. Is this not needed anymore? Since when? Any official docs on that?

Using ScriptEngineManager to eval a class script file returns null

Kotlin version 1.8.20

Simple class defined in a file called simple.kts
class Test {
val x = 5
}

Testing the Script Engine Manager using the following:
@test
fun testClassCompile() {
val scriptReader = this::class.java.classLoader.getResource("simple.kts").openStream().reader()
val engine = ScriptEngineManager().getEngineByExtension("kts")
try {
val result = engine.eval(scriptReader)
assertNotNull(result)
}catch (se: ScriptException) {
fail()
}
}

If I am not mistaken this test should be returning an Object of type Class and not null. Please correct me if I am incorrect or have misunderstood how to get the Class object back.

Consider editing repository setings to remove "Packages" section

"Packages No packages published" is displayed right now, fortunately this pointless section can be removed.

Edit repo page config to remove it (cog next to the description).

I am not making a PR as it is defined in proprietary github settings, not in a git repository - and I have no rights to modify repo settings.

Maybe also releases should be removed

Peek 2020-10-25 09-10

Unable to find extension point configuration extensions/compiler.xml

javax.script.ScriptException: ERROR Unable to initialize repl compiler:
DEBUG Using JDK home inferred from java.home: D:\2_My_Work_Application\graalvm-ce-java17-22.3.0
DEBUG Using JVM IR backend
ERROR Unable to find extension point configuration extensions/compiler.xml (cp:
null): java.lang.IllegalStateException: Unable to find extension point configuration extensions/compiler.xml (cp:
null): java.lang.IllegalStateException: Unable to initialize repl compiler:
DEBUG Using JDK home inferred from java.home: D:\2_My_Work_Application\graalvm-ce-java17-22.3.0
DEBUG Using JVM IR backend
ERROR Unable to find extension point configuration extensions/compiler.xml (cp:
null): java.lang.IllegalStateException: Unable to find extension point configuration extensions/compiler.xml (cp:
null)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.asJsr223EvalResult(KotlinJsr223JvmScriptEngineBase.kt:104)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compileAndEval(KotlinJsr223JvmScriptEngineBase.kt:63)
at kotlin.script.experimental.jvmhost.jsr223.KotlinJsr223ScriptEngineImpl.compileAndEval(KotlinJsr223ScriptEngineImpl.kt:95)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.eval(KotlinJsr223JvmScriptEngineBase.kt:31)
at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:262)
at cn.hutool.script.FullSupportScriptEngine.eval(FullSupportScriptEngine.java:101)
at com.jnvago.jniot.terminal.resolver.subscribe.second.ScriptCache.set(ScriptCache.kt:77)
... 34 common frames omitted

No Simple Example Exists

All these examples are too complicated, brittle, and fragile. Can someone please give the most simple working example possible with only two files

  1. main.kt
  2. script.kts

When I try to run the simple example I get

: wrong number of arguments: 0 expected: 1: java.lang.IllegalArgumentException: wrong number of arguments: 0 expected: 1

Some main.kts examples

If you know good examples of the Kotlin scripting API usage, not mentioned here, please submit an issue or a pull request with the link and short description.

Same examples

Rsocket proxy https://github.com/yschimke/okurl-scripts/blob/master/commands/rsocketTcpProxy.main.kts

Fetch mp3s and download example https://github.com/yschimke/okurl-scripts/blob/master/commands/showList.main.kts

Some requiring external configuration (a token stored by https://github.com/yschimke/okurl/)

A github graphql example https://github.com/yschimke/okurl-scripts/blob/master/commands/github-pull-requests.main.kts
gmail https://github.com/yschimke/okurl-scripts/blob/master/commands/gmail-inbox.main.kts

embeddableTest.kt in jvm-embeddabble-host fails.

When attempting to run the tests in jvm-embeddabble-host the following exception is thrown.

kotlin.script.experimental.jvm.util.ClasspathExtractionException: Unable to get script compilation classpath from context, please specify explicit classpath via "kotlin.script.classpath" property

	at kotlin.script.experimental.jvm.util.JvmClasspathUtilKt.scriptCompilationClasspathFromContext(jvmClasspathUtil.kt:345)
	at kotlin.script.experimental.jvm.JvmScriptCompilationKt.dependenciesFromClassloader(jvmScriptCompilation.kt:57)
	at kotlin.script.experimental.jvm.JvmScriptCompilationKt.dependenciesFromClassloader$default(jvmScriptCompilation.kt:50)
	at kotlin.script.experimental.jvm.JvmScriptCompilationKt.dependenciesFromCurrentContext(jvmScriptCompilation.kt:47)
	at kotlin.script.experimental.jvm.JvmScriptCompilationKt.dependenciesFromCurrentContext$default(jvmScriptCompilation.kt:42)
	at org.jetbrains.kotlin.script.examples.jvm.embeddable.host.HostKt$evalFile$compilationConfiguration$1$1.invoke(host.kt:21)
	at org.jetbrains.kotlin.script.examples.jvm.embeddable.host.HostKt$evalFile$compilationConfiguration$1$1.invoke(host.kt:20)
	at kotlin.script.experimental.util.PropertiesCollection$Builder.invoke(propertiesCollection.kt:282)
	at org.jetbrains.kotlin.script.examples.jvm.embeddable.host.HostKt$evalFile$compilationConfiguration$1.invoke(host.kt:20)
	at org.jetbrains.kotlin.script.examples.jvm.embeddable.host.HostKt$evalFile$compilationConfiguration$1.invoke(host.kt:19)
	at kotlin.script.experimental.host.ConfigurationFromTemplateKt$constructCompilationConfiguration$1.invoke(configurationFromTemplate.kt:113)
	at kotlin.script.experimental.host.ConfigurationFromTemplateKt$constructCompilationConfiguration$1.invoke(configurationFromTemplate.kt:109)
	at kotlin.script.experimental.api.ScriptCompilationConfiguration.<init>(scriptCompilation.kt:22)
	at kotlin.script.experimental.api.ScriptCompilationConfiguration.<init>(scriptCompilation.kt:27)
	at kotlin.script.experimental.host.ConfigurationFromTemplateKt.constructCompilationConfiguration(configurationFromTemplate.kt:109)
	at kotlin.script.experimental.host.ConfigurationFromTemplateKt.createCompilationConfigurationFromTemplate(configurationFromTemplate.kt:67)
	at org.jetbrains.kotlin.script.examples.jvm.embeddable.host.HostKt.evalFile(host.kt:72)
	at org.jetbrains.kotlin.script.examples.jvm.embeddable.test.SimpleTest.testSimple(embeddableTest.kt:20)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
	at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
	at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
	at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

request: sample to get return value of eval

can you add sample to get return value of eval() ?

something like this:

val result : ResultWithDiagnostics<EvaluationResult> = eval(...)

result.castOrError<ResultWithDiagnostics.Success<EvaluationResult>> {
    "script evaluation failed. $it"
}.value.returnValue.castOrError<ResultValue.Value> {
    "script evaluation result is $it"
}.value.castOrError<AppConfig> { // your expected class for value
    "script returns value, but it's not AppConfig. ${it?.javaClass?.simpleName}"
}.let { config = it }

inline fun <reified T:Any> Any?.castOrError(noinline messageCreator:(Any?)->String) =
    (this as? T) ?: error(messageCreator(this))

Show how to configure auto-completion in IntelliJ

Could you please extend the examples to also make auto-completion, e.g. in hello-kotlinx-html.scriptwithdeps.kts, work in IntelliJ?

For example, if I'm extending ScriptWithMavenDeps with a dummy property like

abstract class ScriptWithMavenDeps {
    val dummy: String = "oink"
}

what does it take to offer dummy when typing this. in hello-kotlinx-html.scriptwithdeps.kts?

Caused by: javax.script.ScriptException: Unresolved reference: Import

Hey, what am I doing wrong, if I cannot import in my kts files?

Some pseudocode:

otherfolder/otherfile.kts

fun otherFn() {
  // ...
}

main.kts

@file:Import("otherfolder/otherfile.kts")

fun main() {
  otherFn()
}

I am getting:

Caused by: javax.script.ScriptException: Unresolved reference: Import
Unresolved reference: Import
Unresolved reference: otherFn

This is how I load them in my kotlin/spring app:

        val scriptEngine = ScriptEngineManager().getEngineByExtension("kts")
        val fileReader = FileReader(Paths.get("src/main/resources/main.kts").toFile())
        scriptEngine.eval(fileReader)
        return scriptEngine as Invocable
    kotlin("jvm") version "1.4.21"
    // ...
    implementation( "org.jetbrains.kotlin:kotlin-script-runtime")
    implementation( "org.jetbrains.kotlin:kotlin-script-util")
    implementation( "org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable")
    implementation( "org.jetbrains.kotlin:kotlin-scripting-jvm-host")
    implementation( "org.jetbrains.kotlin:kotlin-scripting-jsr223")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.