从sbt中的依赖项获取资源文件 [英] Get resource file from dependency in sbt

查看:409
本文介绍了从sbt中的依赖项获取资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 sbt-web 项目,其中包含一些webjar和常见的jar依赖项。我想从我的一个jar依赖项获取资源文件,并在连接中使用它任务。但我不知道如何在我的build.sbt中引用依赖jar内的资源。

I have a sbt-web project with some webjar and common jar dependencies. I want to get resource file from one of my jar dependency and use it in concatenation task. But I don't know how refer to the resource inside dependent jar in my build.sbt.

推荐答案

我终于找到了解决方案使用文档。主要思想是在类路径依赖项中找到正确的jar,将其解压缩到temprorary文件夹,并使用此文件执行所需操作。在我的情况下,我将它复制到我的目标目录并在连接任务中使用它。

I finally find the solution with this docs. The main idea is to find the right jar in the classpath dependencies, unzip it to temprorary folder and do what you need with this files. In my case I copy it to my target directory and use it in concatenation task.

我最终得到这个代码:

def copyResourceFromJar(classpathEntry: Attributed[File], jarName: String, resourceName: String) = {
  classpathEntry.get(artifact.key) match {
    case Some(entryArtifact) => {
      // searching artifact
      if (entryArtifact.name.startsWith(jarName)) {
        // unpack artifact's jar to tmp directory
        val jarFile = classpathEntry.data
        IO.withTemporaryDirectory { tmpDir =>
          IO.unzip(jarFile, tmpDir)
          // copy to project's target directory
          // Instead of copying you can do any other stuff here 
          IO.copyFile(
            tmpDir / resourceName,
            (WebKeys.webJarsDirectory in Assets).value / resourceName
          )
        }
      }
    }
    case _ =>
  }
}
for(entry <- (dependencyClasspath in Compile).value) yield {
  copyResourceFromJar(entry, "firstJar", "firstFile.js")
  copyResourceFromJar(entry, "secondJar", "some/path/secondFile.js")
}

此代码应放在任务中。例如:

This code should be placed in the task. For example:

val copyResourcesFromJar = TaskKey[Unit]("copyResourcesFromJar", "Copy resources from jar dependencies")
copyResourcesFromJar := {
  //your task code here
}
copyResourcesFromJar <<= copyResourcesFromJar dependsOn (dependencyClasspath in Compile)

并且不要忘记将此任务添加为构建任务的依赖项。就我而言,它看起来像这样:

And don't forget to add this task as dependcy to your build task. In my case it looks like this:

concat <<= concat dependsOn copyResourcesFromJar

这篇关于从sbt中的依赖项获取资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆