Archive task - use file from classpath


(mrichar2) #1

I have template files that come in as a zip archive from the buildscript dependencies block. I would like to be able to do something like this:

task mytask(type: Copy) {
	from "classpath:/templates/v1/mytemplate.json"
	expand([ ... ])
}

It would be great if ‘from’ could have an easy way to pull files from the classpath.

The closest thing I have found to be able to do this is here: Best practice for copying files from classpath. That however is almost 2 years old. Is there a better way to do what I want without having to write several lines of groovy code?


(mrichar2) #2

This is the best I could come up with (assuming one item on classpath):

def templates = zipTree(buildscript.configurations.classpath.first()).matching({ "**/templates/v1/*" }).files;

task mytask(type: Copy) {
	from "mytemplate.json"
	expand([ ... ])
}

(uklance) #3

You’d typically use a configuration

configurations {
   myconfig
} 
dependencies {
   myconfig 'foo.bar:baz:1.0'
}
task foo(type: Copy) {
   from zipTree(configurations.myconfig.singleFile).matching { 
      include "**/templates/v1/*" 
   } 
  ... 
} 

(Sohrab Hosseini) #4

Recently I had to create a new custom plugin and did a search around to see if a better way than my two year old “technique” from the other post but unfortunately nothing came up. The suggestions here are as good as it gets right now I think :unamused:


(Justin Klaassen) #5

This solution worked well for me in a custom buildSrc plugin with resources:

static File getResource(Project project, String name) {
    final URL resource = this.classLoader.getResource(name)
    if (resource.protocol == 'jar') {
        final JarURLConnection jar = resource.openConnection()
        project.resources.text.fromArchiveEntry(jar.jarFileURL.file, jar.entryName).asFile()
    } else {
        project.file(resource.file)
    }
}