如何缓存sbt TaskKey的结果?

时间:2014-08-20 17:01:26

标签: scala sbt

我需要在测试中引用一项昂贵的任务

lazy val exampleSources = TaskKey[Seq[File]]("exampleSources", "for use in tests")

exampleSources := (updateClassifiers in Test).value.select(
  artifact = artifactFilter(classifier = "sources")
)

(然后我可以将exampleSources.value作为参数传递给我的分叉测试)

但是,每次运行测试时,都会调用此任务,并调用updateClassifiers(昂贵)。但我很高兴在第一次通话时缓存该值,然后将其用于会话。

如果不自己编写缓存,有没有办法使用内置的sbt对象?

更新:这不起作用。第二次评估有CACHE=true,但解决任务仍然有效。

lazy val infoForTests = TaskKey[Seq[String]]("infoForTests", "for use in tests")

val infoForTestsCache = collection.mutable.Buffer[String]()

infoForTests := {
  println("CACHE=" + infoForTestsCache.nonEmpty)
  if (infoForTestsCache.isEmpty) {
    infoForTestsCache ++= Seq[String](
      "-Densime.compile.jars=" + jars((fullClasspath in Compile).value),
      "-Densime.test.jars=" + jars((fullClasspath in Test).value),
      "-Densime.compile.classDirs=" + classDirs((fullClasspath in Compile).value),
      "-Densime.test.classDirs=" + classDirs((fullClasspath in Test).value),
      "-Dscala.version=" + scalaVersion.value,
      // sorry! this puts a source/javadoc dependency on running our tests
      "-Densime.jars.sources=" + (updateClassifiers in Test).value.select(
        artifact = artifactFilter(classifier = "sources")
      ).mkString(",")
    )
    println("CACHE=" + infoForTestsCache.nonEmpty)
  }
  infoForTestsCache
}

1 个答案:

答案 0 :(得分:1)

您可以使用FileFunction.cached缓存结果,仅在输入更改时才能正常工作。

链接的sbt文档中的一个示例:

// define a task that takes some inputs
//   and generates files in an output directory
myTask := {
    // wraps a function taskImpl in an uptodate check
    //   taskImpl takes the input files, the output directory,
    //   generates the output files and returns the set of generated files
    val cachedFun = FileFunction.cached(cacheDirectory.value / "my-task") { (in: Set[File]) =>
      taskImpl(in, target.value) : Set[File]
    }
    // Applies the cached function to the inputs files
    cachedFun(inputs.value)
}

您可能还想查看我对类似问题的回答:How to list files output by incremental recompilation