can i somehow AOT-compile my script into a jar or ...
# scripting
j
can i somehow AOT-compile my script into a jar or set of jars to run somewhere without kotlin available? would also be nice to be able to produce something that I can feed into graal native-image. Passing
-d out
has no effect, and obviously I cannot compile without
-script
.
it ain't pretty but i did
Copy code
KOTLIN_MAIN_KTS_COMPILED_SCRIPTS_CACHE_DIR=/path/to/build my-script.main.kts || true
mv /path/to/build/*.jar script.jar
i have no idea if it works on scripts with dependencies, and thankfully mine errors with no arguments so there's no side-effects
-include-runtime
doesn't work with
-script
😬
k
FWIW, you can build a fat jar with kscript
Never tried feeding it into native-image though 🤔
j
I don't want to use kscript. That's like solving one problem by adding another. I'm trying to solve for the problem when you don't have Kotlin in the first place so not having kscript is even more likely (if not a given). I gave up and switched to a normal Gradle project that I run through R8 to get a minified jar. Only 38KB!
👍 1
😮 1
a
I think it is possible to make an inforstucture for simple packing and running of single-file artifacts on top of gralde. It would be nice to have.
i
There is no out-of-box solution yet (please add an YT issue if you think it is important feature to have) But there are two approaches that can bring you some partial solution: -
kotlinc
treats scripts the same way as regular kotlin sources, if you will omit the
-script
argument, so you can compile your script into a jar with any options you want. But then you need a way to instantiate the script, in particular pass the proper set of args to the constructor. The
main
function will be generated automatically and will try to convert
args
to the constructor arguments, but it is not always reliable. And also the manifest attribute for the
main class
is not set properly in this case. But yon the other hand, you can make an additional
.kt
file with the proper
main
and compile it along with the script. - you can use a custom scripting host instead of the
kotlinc
, compile script with compiler class and then save it with e.g.
saveToJar
helper. This will create a runnable jar. (Actually
main-kts
cache contains jars generated with this helper, therefore the hack with extracting jar from it works). The manifest of this jar contain links to all dependencies in the
class-path
, but to make it self-contained, you may need to create your own helper similar to
saveToJar
.
👍 1
j
Interesting I assumed it would fail to compile since
args wouldn't be resolved (sorry Slack trapped me in dumb monospace)