如何将Scala版本字符串传递给SBT的代码生成器?

时间:2014-10-21 17:52:36

标签: scala sbt

使用带有SBT的代码生成器时,可以使用

之类的结构
def genFile(out: File): Seq[File] = {
  val file = new File(out, "generated.scala")
  // Add stuff to file
  Seq(file)
}

(sourceGenerators in Compile) <+= (sourceManaged in Compile) map (genFile _)

如果你的生成器需要Scala版本字符串,你如何传递它?在scalaVersion.value中使用genFile会导致错误。

1 个答案:

答案 0 :(得分:2)

这是很好的老路。我确信有一种更新的方法可以将genFile定义为自定义任务,并启用scalaVersion.value

// build.sbt
scalaVersion := "2.11.2"

def genFile(out: File, v: String): Seq[File] = {
  out.mkdirs()
  val f = out / "generated.scala"
  val w = new java.io.FileOutputStream(f)
  w.write(s"""package object foo {
             |  val scalaVersion = "$v"
             |}
             |""".stripMargin.getBytes("UTF-8"))
  w.close()
  Seq(f)
}

(sourceGenerators in Compile) <+=
  (sourceManaged in Compile, scalaVersion in Compile) map genFile

$ sbt console
...
[info] Starting scala interpreter...
[info] 
Welcome to Scala version 2.11.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_65).
Type in expressions to have them evaluated.
Type :help for more information.

scala> foo.scalaVersion
res0: String = 2.11.2