Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get resource file from dependency in sbt

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.

like image 289
LMnet Avatar asked Mar 15 '23 10:03

LMnet


1 Answers

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.

I end up with this code:

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
like image 144
LMnet Avatar answered Mar 18 '23 02:03

LMnet