Is there a way to "extend" main.kts? I want to cr...
# scripting
r
Is there a way to "extend" main.kts? I want to create my own script definition (compiler plugin + context), but use dependencies and imports. Dependencies is in a separate artifact, so that's easy enough to use, but is there any way to do the same for the rest of the stuff in main.kts?
b
Why not just use @file:Import() and @file: Dependency () annotations in normal kts files?
r
Does that work? I was under the impression they only worked in
.main.kts
files, and only if you're using the main-kts script definition (that's where it's implemented, see https://github.com/JetBrains/kotlin/blob/master/libraries/tools/kotlin-main-kts/src/org/jetbrains/kotlin/mainKts/scriptDef.kt)
b
this works
Copy code
#!/usr/bin/env kotlinc -script
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0")
import kotlinx.coroutines.runBlocking
*.main.kts is just a conventions to implicitly apply -script flag
👀 1
Shebang line achieves the same, no matter how the file is named
You can then name it whatever and run it as
./whatever
(might need to do
chmod +x whatever
first)
r
I'm not going to be running via
kotlinc
, is the issue
I'm going to (I think) have a application (and daemon, eventually) that compiles and runs the script
b
Hmm, that uses kotlin-compiler-embeddable, then. Not sure, but that should support those annotations too. Give it a test
r
I haven't actually ran it, but I'm 99% it doesn't, you can see the annotations are only handled in the
kotlin-main-kts
script def (see the earlier github link), and are declared in
kotlin-main-kts
and
kotlin-scripting-dependencies
.
b
You're right. I'm clearly out of my depth here.
i
@rnett, the main-kts itself is not designed to be extendable, but all the components are available for use independently. There is an example project - https://github.com/Kotlin/kotlin-script-examples/blob/master/jvm/simple-main-kts/SimpleMainKts.md - that have most features of the main.kts (except jsr-223 integration), so you can use it as a starting point. I would only recommend to use
kotlin-scripting-dependencies-maven
instead of the ivy resolver. We will switch to the maven resolver soon in all projects too.
r
Thanks, that should be enough. Has there been any discussion of extracting
Import
and
CompilerOptions
to separate dependencies like has been done for dependency resolution? Should I make a youtrack issue?
i
Creating an issue is a good idea, at least for the further tracking. But I'm not sure it will happen soon, at least with
Import
- there are several open questions there, e.g. IDE support.
r
Makes sense, that's part of the reason I was hoping I could crib off of main-kts