How to copy some files to the build target directory with SBT?

余生颓废 提交于 2019-12-30 06:23:25

问题


How can I copy some source files (e.g. /src/main/html/*.html) to the build output directory (e.g. /target/scala-2.11/) with SBT so that the files end up in the target root and not in the classes subdirectory (which is what happens if I add the source directory to unmanagedResourceDirectories)?


回答1:


You can define sbt task copying resources to target directory:

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)
    )
  }
)

and use this task in sbt:

sbt clean package copyRes



回答2:


One way would be to first collect all files you wish to copy, using for example a PathFinder and use one of the copy methods in sbt.io.IO combined with Path.rebase

For the specific example in the question:

// 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


来源:https://stackoverflow.com/questions/36237174/how-to-copy-some-files-to-the-build-target-directory-with-sbt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!