定义从项目代码调用方法的 sbt 任务? [英] Defining sbt task that invokes method from project code?
问题描述
我正在使用 SBT 构建一个 Scala 项目.我想定义一个非常简单的任务,当我在 sbt 中输入 generate
时:
I'm using SBT to build a scala project. I want to define a very simple task, that when I input generate
in sbt:
sbt> generate
它将调用我的 my.App.main(..)
方法来生成一些东西.
It will invoke my my.App.main(..)
method to generate something.
myproject/src/main/scala/my
中有一个App.scala
文件,简化后的代码是这样的:
There is a App.scala
file in myproject/src/main/scala/my
, and the simplified code is like this:
object App {
def main(args: Array[String]) {
val source = readContentOfFile("mysource.txt")
val result = convert(source)
writeToFile(result, "mytarget.txt");
}
// ignore some methods here
}
我尝试将以下代码添加到 myproject/build.sbt
中:
I tried to add following code into myproject/build.sbt
:
lazy val generate = taskKey[Unit]("Generate my file")
generate := {
my.App.main(Array())
}
但是它无法编译,因为它找不到 my.App
.
But which doesn't compile since it can't find my.App
.
然后我尝试将它添加到myproject/project/build.scala
:
Then I tried to add it to myproject/project/build.scala
:
import sbt._
import my._
object HelloBuild extends Build {
lazy val generate = taskKey[Unit]("Generate my file")
generate := {
App.main(Array())
}
}
但是还是不能编译,找不到包my
.
But it still can't be compiled, that it can't find package my
.
如何在 SBT 中定义这样的任务?
How to define such a task in SBT?
推荐答案
在 .sbt
格式中,执行:
lazy val generate = taskKey[Unit]("Generate my file")
fullRunTask(generate, Compile, "my.App")
这记录在 http://www.scala-sbt.org/0.13.2/docs/faq.html, 除了运行之外,如何创建自定义运行任务?"
This is documented at http://www.scala-sbt.org/0.13.2/docs/faq.html, "How can I create a custom run task, in addition to run?"
另一种方法是:
lazy val generate = taskKey[Unit]("Generate my file")
generate := (runMain in Compile).toTask(" my.App").value
在简单的情况下工作正常,但不是可定制的.
which works fine in simple cases but isn't as customizable.
更新:Jacek 建议改用 resourceGenerators
或 sourceGenerators
是好的,如果它适合您的用例 - 无法从您的说明是否有.
Update: Jacek's advice to use resourceGenerators
or sourceGenerators
instead is good, if it fits your use case — can't tell from your description whether it does.
这篇关于定义从项目代码调用方法的 sbt 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!