生成用于编译和测试的资源

时间:2015-08-09 20:22:29

标签: scala sbt

我打算根据模板和sbt设置生成资源。 GL_TRIANGLESGL_TRIANGLE_STRIP应该有不同的sbt设置。模板位于Compile。在sbt-dev gitter聊天中,我建议使用Testproject/resources/hdfs/*.xml,但我无法让它工作。

到目前为止

代码:

Setting

错误:

inConfig

下一次迭代,我不知道如何获取范围val hdfsNamenode = settingKey[String]("Namenode for the HDFS access") def genHdfsConfigs: Setting[_] = hdfsNamenode := { resourceGenerators += Def.task { val files = ((baseDirectory.value / "project" / "resources" / "hdfs" ) * "*.xml").get files.foreach({ hdfsTemplate => val config = IO.read(hdfsTemplate).replace("{{namenode}}", hdfsNamenode.value) IO.write(resourceManaged.value / hdfsTemplate.getName, config) }) files.toSeq }.taskValue } hdfsNamenode in Test := "localhost" hdfsNamenode in Compile := "172.31.32.228" def allHdfsNamenodeConfigs: Seq[Setting[_]] = inConfig(Compile)(Seq(hdfsNamenode)) ++ inConfig(Test)(Seq(hdfsNamenode)) / [error] found : sbt.Def.Setting[Seq[sbt.Task[Seq[java.io.File]]]] [error] required: String [error] resourceGenerators += Def.task { [error] ^ [error] found : sbt.SettingKey[String] [error] required: sbt.Def.Setting[_] [error] inConfig(Compile)(Seq(hdfsNamenode)) ++ inConfig(Test)(Seq(hdfsNamenode)) [error] 中的hdfsNameNode而不是未范围内的。{/ p>

Compile

当前(丑陋)解决方案:

Test

1 个答案:

答案 0 :(得分:6)

在定义资源生成器时,只需将Configuration作为参数传递。

val hdfsTestNameNode = "localhost"
val hdfsMainNameNode = "172.31.32.228"

val hdfsNameNode = settingKey[String]("Namenode for the HDFS access")

def genHdfsConfig(cfg: Configuration) = Def.task {
  val files = ((baseDirectory.value / "project" / "templates" / "resources" / "hdfs" ) * "*.xml").get
  files.map({ hdfsTemplate =>
    val config = IO.read(hdfsTemplate).replace("{{namenode}}", (hdfsNameNode in cfg).value)
    val outputPath = (resourceManaged in cfg).value / hdfsTemplate.getName
    IO.write(outputPath, config)
    outputPath
  })
}

Seq(
  hdfsNameNode in Test := hdfsTestNameNode,
  hdfsNameNode in Compile := hdfsMainNameNode,
  resourceGenerators in Compile += genHdfsConfig(Compile).taskValue,
  resourceGenerators in Test += genHdfsConfig(Test).taskValue
)

不想指定范围两次?只需重构一下。

val hdfsTestNameNode = "localhost"
val hdfsMainNameNode = "172.31.32.228"

val hdfsNameNode = settingKey[String]("Namenode for the HDFS access")

def addHdfsConfigGenerator(cfg: Configuration) = {
  inConfig(cfg) {
    val hdfsConfigGenerator = Def.task {
      val files = ((baseDirectory.value / "project" / "templates" / "resources" / "hdfs" ) * "*.xml").get
      files.map({ hdfsTemplate =>
        val config = IO.read(hdfsTemplate).replace("{{namenode}}", (hdfsNameNode in cfg).value)
        val outputPath = (resourceManaged in cfg).value / hdfsTemplate.getName
        IO.write(outputPath, config)
        outputPath
      })
    }
    resourceGenerators += hdfsConfigGenerator.taskValue
  } last
}

Seq(
  hdfsNameNode in Test := hdfsTestNameNode,
  hdfsNameNode in Compile := hdfsMainNameNode,
  addHdfsConfigGenerator(Compile),
  addHdfsConfigGenerator(Test)
)