方案:
- 一个Gradle项目,使用
org.jetbrains.kotlin.jvm
插件
- 该项目具有一些
*。kts
kotlin脚本文件,位于 src/main/kotlin中
。脚本执行各种任务,例如,有一个脚本可以从一组CSV文件加载到本地H2数据库中的测试数据,一个用于在数据库中创建测试用户的脚本等。
- 我当前使用Intellij Idea Idea Rul Run Configurations运行这些脚本
- Gradle Build文件使用KotlinScript(
build.gradle.kts
),
以使新开发人员更易于设置功能,我想配置Gradle,以便我可以使用Gradle直接运行脚本。这将简化我的 readme.md
,而不是“使用Intellij用参数yyy和zzz执行脚本xxx.kts,然后是nnn.kts”,而是可以编写“ Execute” execute gradle loadTestDataTaTaTaintAtolocalH2Database”。
问题/问题:
- 是否有一种简单的方法来执行Gradle的
*。KTS
脚本?
Scenario:
- A gradle project, using the
org.jetbrains.kotlin.jvm
plugin
- The project has some
*.kts
kotlin script files located inside src/main/kotlin
. The scripts do various tasks, for instance there is a script for loading test data from a set of CSV files into a local H2 database, a script for creating a test user in the database etc.
- I currently run these scripts using IntelliJ IDEA run configurations
- The gradle build file is using kotlinscript (
build.gradle.kts
)
To make things easier to set up for new developers, I would like to configure gradle so I can run the scripts directly using gradle. That would simplify my README.md
, instead of "use IntelliJ to execute the script xxx.kts with arguments yyy and zzz, then nnn.kts", I could write "execute gradle loadTestDataIntoLocalH2Database".
Questions/issues:
- Is there a simple way to execute a
*.kts
script from gradle?
发布评论
评论(1)
Puzzled my answer together from https://docs.gradle.org/current /userguide/plugins.html#sec:script_plugins ,和
尽管我没有尝试过,但如果您可以将脚本添加到项目包中,而不是将它们保留为宽松的脚本,那么第二个链接似乎是最好的解决方案。
用Gradle 7.2测试。
第一个选项是最直接的,没有代码的更改,但要求您安装Kotlin编译器CLI(KOTLINC),然后Gradle可以调用它执行脚本:
然后使用
grad> gradle -q mytask
调用它。 。或显然您还可以提供直接说明,以便为用户运行kotlinc,而无需将其包裹在Gradle中。第二个选项是将脚本加载为插件。但是,这会导致Kotlinscript注释,例如外部导入(@file:导入等)不起作用。
将代码包装在脚本中:
在构建脚本中加载为插件:
apply(from =“ foo.kts”)
然后使用
gradle -q mytask
调用它。Puzzled my answer together from https://docs.gradle.org/current/userguide/plugins.html#sec:script_plugins , https://kotlinexpertise.com/execute-kotlin-scripts-with-gradle/ and https://stackoverflow.com/a/52139585/9936828
Although I didn't try it, the second link seems like the best solution if you are ok with adding the scripts to your projects package instead of keeping them as loose scripts.
Tested with gradle 7.2.
First option is the most straightforward with no changes to code, but requires you to install the kotlin compiler CLI (kotlinc), gradle can then call it to execute the scripts:
Then call it with
gradle -q MyTask
. Or obviously you could also provide the direct instructions to run kotlinc for the user without wrapping it in gradle.Second option would be to load your script as a plugin. This however causes the kotlinscript annotations such as external imports (@file:Import, etc) to not work.
Wrap your code in your script in a task:
load as plugin in your build script:
apply(from = "foo.kts")
Then call it with
gradle -q MyTask
.