跟踪SBT中的文件更改

时间:2019-06-07 06:29:08

标签: scala sbt

我正在使用Tracked._来包装资产构建任务(Webpack),以便它仅在输入或输出文件发生更改时才运行。它可以正常工作,只是如果更改了输入文件,任务将运行两次,然后再意识到它不需要运行。更改输出文件可以正常工作-只能运行一次。

我设置错了吗? Tracked._的用法的一般结构与Scaladoc中的用法完全相同。

import sbt._
import sbt.Tracked.{inputChanged, outputChanged}
import sbt.util.FileInfo.lastModified

object Changes {
  /**
    Monitors inputDir and outputDir, tracking the state in cacheDir and
    running fn if there are any changes
  */
  def ifChanged(cacheDir: File, inputDir: File, outputDir: File)(fn: => Unit) = {
    val cachedTask = inputChanged(cacheDir / "inputs") { (inChanged, in: FilesInfo[ModifiedFileInfo]) =>
      outputChanged(cacheDir / "output") { (outChanged, outputs: FilesInfo[ModifiedFileInfo]) =>
        if (inChanged || outChanged) {
          fn
        }
      }
    }
    cachedTask(lastModified(inputDir.allPaths.get.toSet))(() => lastModified(outputDir.allPaths.get.toSet))
  }
}

然后在build.sbt中使用:

lazy val webpack = taskKey[Unit]("Run webpack when packaging the application")

def runWebpack(file: File): Int = Process("npm run build", file).!

webpack := {
  Changes.ifChanged(
    target.value / "webpack-tracking",
    baseDirectory.value / "app" / "assets",
    target.value / "assets"
  ) {
    if (runWebpack(baseDirectory.value) != 0) 
      throw new Exception("Webpack error")
  }
}

0 个答案:

没有答案