SBT:输入任务以按名称生成测试源

时间:2015-05-09 10:07:10

标签: scala sbt

我想创建一个sbt任务来生成测试源,例如sbt genSpec Foo应在src_managed / test

中生成FooSpec.scala

我试过了:

val genSpec = inputKey[File]("Generate spec file")

genSpec := {
  import sbt.complete.DefaultParsers._
  val log = streams.value.log
  val arg: String = spaceDelimited("<arg>").parsed.head //TODO: Single string parser!
  val fileName = s"${arg}Spec"
  log.info(s"Generating $fileName")
  val file = (sourceManaged in Test).value / s"$fileName.scala"
  IO.write(file, s"""class $fileName extends AbstractSpec""")
  //sourceGenerators in Test += file
  file
}

但是,即使它是在sourceManaged目录中创建的,sbt test也不会把它拿起来。

但是,这有效:

sourceGenerators in Test += Def.task {
  val file = (sourceManaged in Test).value / "FooSpec.scala"
  IO.write(file, s"""class FooSpec extends AbstractSpec""")
  Seq(file)
}.taskValue

但是,以上并不是我想要的 - 我想将Foo指定为参数。

那么,有没有办法将参数传递给sourceGenerator任务?或者创建一个向托管来源添加内容的任务,以便通过sbt test获取它?

此外,迭代所有已编译源的文件名的方法是什么?如果我能做到这一点,我将简单地从源文件名本身生成所有Spec.scala ...

根据this question的建议,我试过了这个:

val genSpec = taskKey[Seq[File]]("Generate spec file")

genSpec := {
  import sbt.complete.DefaultParsers._
  val log = streams.value.log
  val args = spaceDelimited("<arg>").parsed
  args map {arg =>
    val fileName = s"${arg}Suite"
    log.info(s"Generating $fileName")
    val file = (sourceManaged in Test).value / s"$fileName.scala"
    IO.write(file, s"""class $fileName extends AbstractSuite""")
    file
  }
}


genSpec <<= (sourceGenerators in Test) { _.join.map(_.flatten.toList) }

但是,我收到了这个错误:

 error: `parsed` can only be used within an input task macro, such as := or Def.inputTask.
  val args = spaceDelimited("<arg>").parsed
                                     ^

1 个答案:

答案 0 :(得分:0)

试试这个:

val genSpec = inputKey[File]("Generate spec file")

genSpec := {
  import sbt.complete.DefaultParsers._
  val log = streams.value.log
  val arg: String = spaceDelimited("<arg>").parsed.head //TODO: Single string parser!
  val className = s"${arg}Spec"
  val file = (sourceManaged in Test).value / s"$className.scala"
  log info s"Generating $file"
  IO.write(file, s"""class $className extends AbstractSpec""")
  file
}

managedSources in Test ++= ((sourceManaged in Test).value ** "*Spec.scala").get