How to override where some files are written to in the jar file?

In my build script, after the classes are compiled, I need to construct a jar containing the compiled classes, and also the contents of “src/main/resources”, but instead of copying everything in “src/main/resources” into the root of the jar, I need them all copied into the “META-INF” folder of the jar. Actually, in my project there is a subfolder of “src/main/resources” that I actually care about, and that folder needs to be copied into the META-INF folder. Technically, if I had other files in “src/main/resources” besides that one folder, I would be fine with those being copied into the root of the jar, as long as that one subfolder is copied to the “META-INF” folder.

I’ve tried the following:

jar {
 from ("src/main/resources/yang") {
  into ("META-INF/yang")
 }
 }

This sort of works. The files in “src/main/resources/yang” do get copied into “META-INF/yang” in the jar. However, those same files are also copied into a “yang” folder in the root directory of the jar. Those are just wasting space. I’d prefer that those files not be in the resulting jar in that location, only in the “META-INF/yang” folder.

You can use ‘eachFile’ to override the target path.

jar {
        includeEmptyDirs = false
        eachFile { details ->
            if (details.path.startsWith('yang')) {
                details.path = "META-INF/$details.path"
            }
        }
    }

Interesting.I found a different solution that looks like this:

jar {
 exclude "yang"
 from ("src/main/resources/yang") {
  into ("META-INF/yang")
 }
 }

I can see the advantages of your approach. In reality, though, I really need to make this happen in my plugin code, not in the build script. I did this with the following:

Jar jarTask = project.jar
jarTask.exclude("yang")
jarTask.from(task.yangFilesRootDir) { into("META-INF/yang") }

I can see that integrating your solution in theplugin would be just as easy.