简体   繁体   中英

Gradle and Shadow plugin - copy additional files (.jar files) to final jar after shadowJar task

Problem description :
I'm using Gradle Shade plugin, it all works fine and it copies resource files to the final jar. However, as the docs say, it can not include other .jar files as resources because it can not distinguish them from dependencies. It unpacks them isntead.

What I want to do :
I want to copy extra .jar files from tools folder (which lives next to my build.gradle ) into the final jar produced by shadowJar task.

Question :
How to extend a task ( shadowJar ) to copy additional files into the produced jar file.

This is answered in the documentation of the Gradle shadow plugin, section Embedding Jar Files Inside Your Shadow Jar :

[...] shadow is unable to distinguish between a jar file configured as a dependency and a jar file included in the resource folder. This means that any jar found in a resource directory will be merged into the shadow jar the same as any other dependency. If your intention is to embed the jar inside, you must rename the jar as to not end with .jar before the shadow task begins.

Unfortunately, this holds both for a JAR that is part of a dependency configuration as well as copying a JAR using a from copy spec (which works since the shadowJar task extends the jar task; which in turn is a copy task and hence supports copy specs).

So, a JAR can only be embedded by renaming it. If it must be named .jar inside the Uber JAR, I think the only option is a three-step workaround:

  1. Create the Uber JAR and embed JARs by renaming them; eg, use the suffix *.zip .
shadowJar
{
    from("${dirThatContainsSomeJARs}")
    {
        include '*.jar'
        rename '(.+).jar', '$1.zip'
    }
}
  1. Unpack the Uber JAR and rename all JARs that have been embedded as *.zip back to *.jar .
  2. Repack everything again using the jar or zip task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM