2015-05-09 51 views
0

我想創建一個sbt任務來生成測試源,例如sbt genSpec Foo應該產生FooSpec.scala在src_managed /測試SBT:按名稱生成測試源的輸入任務

我嘗試這樣做:

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測試不把它撿起來。

但是,這個工程:

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

不過,上述不正是我想要的 - 我想指定符作爲參數。

那麼,有沒有辦法將參數傳遞給sourceGenerator任務?或者創建一個任務,將某些東西添加到託管源代碼中,以便通過sbt測試獲取它?

另外,什麼是迭代所有編譯源文件名的方法?如果我能做到這一點,我會簡單地從源文件名本身產生的所有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 
            ^

回答

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