且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何避免重新编译生成的源代码

更新时间:2023-09-19 20:00:28

您希望使用 FileFunction.cached 以便不会每次都重新生成源文件.

You want to use FileFunction.cached so that the source files aren't regenerated every time.

这是我自己构建的示例:

Here's an example from my own build:

Compile / sourceGenerators += Def.task[Seq[File]] {
  val src = (Compile / sourceManaged).value
  val base = baseDirectory.value
  val s = streams.value
  val cache =
    FileFunction.cached(s.cacheDirectory / "lexers", inStyle = FilesInfo.hash, outStyle = FilesInfo.hash) {
      in: Set[File] =>
        Set(flex(s.log.info(_), base, src, "ImportLexer"),
            flex(s.log.info(_), base, src, "TokenLexer"))
    }
  cache(Set(base / "project" / "flex" / "warning.txt",
            base / "project" / "flex" / "ImportLexer.flex",
            base / "project" / "flex" / "TokenLexer.flex")).toSeq
}.taskValue

这里的 .txt.flex 文件是生成器的输入文件.生成源文件的实际工作交给了我的 flex 方法,它返回一个 java.io.File:

Here the .txt and .flex files are input files to the generator. The actual work of generating the source files is farmed out to my flex method, which returns a java.io.File:

def flex(log: String => Unit, base: File, dir: File, kind: String): File =
  ...

您应该能够将这种技术应用于您的构建.

You should be able to adapt this technique to your build.

FileFunction.cached 在 API 文档和 sbt FAQ 中的如果输入文件不变,任务如何避免重做工作?"下有描述.(http://www.scala-sbt.org/0.13/docs/Faq.html).(如果关于缓存的材料是从 http://www.scala-sbt.org/0.13/docs/Howto-Generating-Files.html 也是;目前不是.)

FileFunction.cached is described in the API doc and in the sbt FAQ under "How can a task avoid redoing work if the input files are unchanged?" (http://www.scala-sbt.org/0.13/docs/Faq.html). (It would be nice if the material on caching was referenced from http://www.scala-sbt.org/0.13/docs/Howto-Generating-Files.html as well; currently it isn't.)