如何使用SBT将一些文件复制到构建目标目录?

时间:2016-03-26 15:34:01

标签: scala sbt

如何使用SBT将一些源文件(例如/src/main/html/*.html)复制到构建输出目录(例如/target/scala-2.11/),以便文件最终位于目标根目录中而不是在classes子目录中(如果我将源目录添加到unmanagedResourceDirectories会发生什么情况)?

2 个答案:

答案 0 :(得分:6)

您可以将sbt任务复制资源定义到目标目录:

lazy val copyRes = TaskKey[Unit]("copyRes")

lazy val root:Project = Project(
   ...
)
.settings(
  ...
  copyRes <<= (baseDirectory, target) map {
    (base, trg) => new File(base, "src/html").listFiles().foreach(
      file => Files.copy(file.toPath, new File(trg, file.name).toPath)
    )
  }
)

并在sbt:

中使用此任务
sbt clean package copyRes

答案 1 :(得分:1)

一种方法是首先收集您要复制的所有文件,例如使用PathFinder,然后使用copy中的sbt.io.IO方法之一与Path.rebase组合使用

对于问题中的具体示例:

// Define task to  copy html files
val copyHtml = taskKey[Unit]("Copy html files from src/main/html to cross-version target directory")

// Implement task
copyHtml := {
  import Path._

  val src = (Compile / sourceDirectory).value / "html"

  // get the files we want to copy
  val htmlFiles: Seq[File] = (src ** "*.html").get()

  // use Path.rebase to pair source files with target destination in crossTarget
  val pairs = htmlFiles pair rebase(src, (Compile / crossTarget).value)

  // Copy files to source files to target
  IO.copy(pairs, CopyOptions.apply(overwrite = true, preserveLastModified = true, preserveExecutable = false))

}

// Ensure task is run before package
`package` := (`package` dependsOn copyHtml).value