【发布时间】:2016-07-14 05:26:35
【问题描述】:
如何使用 SBT 将一些源文件(例如 /src/main/html/*.html)复制到构建输出目录(例如 /target/scala-2.11/),以便文件最终位于 目标根目录而不是classes 子目录(如果我将源目录添加到unmanagedResourceDirectories 会发生什么情况)?
【问题讨论】:
如何使用 SBT 将一些源文件(例如 /src/main/html/*.html)复制到构建输出目录(例如 /target/scala-2.11/),以便文件最终位于 目标根目录而不是classes 子目录(如果我将源目录添加到unmanagedResourceDirectories 会发生什么情况)?
【问题讨论】:
您可以定义 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
【讨论】:
File.listFiles 只返回直系后代。
一种方法是首先收集您要复制的所有文件,例如使用PathFinder,然后使用sbt.io.IO 中的copy 方法之一与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
【讨论】: