【问题标题】:How to copy some files to the build target directory with SBT?如何使用 SBT 将一些文件复制到构建目标目录?
【发布时间】:2016-07-14 05:26:35
【问题描述】:

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

【问题讨论】:

    标签: scala sbt


    【解决方案1】:

    您可以定义 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
    

    【讨论】:

    • 文件的导入是什么?另外,我尝试将“target”硬编码为表示相对于 baseDirectory 的目录的字符串,但这似乎不起作用。
    • java.nio.file.Files
    • 另请注意,这可能不是递归的。 File.listFiles 只返回直系后代。
    【解决方案2】:

    一种方法是首先收集您要复制的所有文件,例如使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多