Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

scala - Defining sbt task that invokes method from project code?

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

It will invoke my my.App.main(..) method to generate something.

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
}

I tried to add following code into myproject/build.sbt:

lazy val generate = taskKey[Unit]("Generate my file")

generate := {
  my.App.main(Array())
}

But which doesn't compile since it can't find my.App.

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())
  }

}

But it still can't be compiled, that it can't find package my.

How to define such a task in SBT?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In .sbt format, do:

lazy val generate = taskKey[Unit]("Generate my file")

fullRunTask(generate, Compile, "my.App")

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?”

Another approach would be:

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...